首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >单击时会更改页面背景的预览按钮?

单击时会更改页面背景的预览按钮?
EN

Stack Overflow用户
提问于 2014-10-16 10:00:35
回答 3查看 87关注 0票数 1

我运行了一个提供可平铺/无缝图案的免费资源站点,我正在尝试在我的帖子中添加一个按钮(带有脚本),访问者可以点击这个按钮来更改页面的背景图像,以便他们可以预览运行中的图案。例如,在这篇文章(http://tileablepatterns.com/denim-pattern/)上,我希望用户能够点击一个按钮/链接,它会将背景图像从灰色背景更改为牛仔图案。

我该怎么做呢?此外,最好是我希望它是一个简单的脚本,我可以只插入到帖子中,而不是必须编辑主题文件。

非常感谢您的帮助!

EN

回答 3

Stack Overflow用户

发布于 2014-10-16 10:10:35

给你的按钮一个ID,例如: id=" button“,然后下面的代码就会起作用:

代码语言:javascript
复制
$('#button').click(function(){ $('body').css('background', 'url(http://tileablepatterns.com/wp-content/uploads/2014/09/Denim.jpg) repeat 0 0'); });
票数 1
EN

Stack Overflow用户

发布于 2014-10-16 10:57:12

所以基本上我尝试了这个<button onclick="document.body.style.background = 'url(http://tileablepatterns.com/wp-content/uploads/2014/09/Denim.jpg) no-repeat center center'">change bg</button>

它在现有背景中添加了两条白线,一条靠近顶部,一条靠近底部,但它不会改变整个背景。我认为有一个包装器覆盖在背景上,但我不知道如何更改代码,使其改变整个页面的背景,包括包装器?

票数 1
EN

Stack Overflow用户

发布于 2014-10-16 11:10:58

如果我要使用jQuery来做这件事,我会采用一种模块化的方法,这种方法很容易在HTML中模板化,并且在Javascript失败的情况下仍然有效。

从一些基本标记开始(我使用Baconmockup作为示例图像):

代码语言:javascript
复制
<div id="page" class="container">
    <!-- Note that we're defining both href as well as two html5 attributes called data-src and data-background-change (data-background-change is what indicates that this particular link has some special functionality and data-src is the the source for the script below) -->
    <a href="https://s3.amazonaws.com/baconmockup/img/baconmockup-470-300.jpg" data-src="https://s3.amazonaws.com/baconmockup/img/baconmockup-470-300.jpg" data-background-change>Click me</a>
</div>

和一些CSS:

代码语言:javascript
复制
// The container is your page, and the background we'll change in this example.
div.container {
    background: red;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
}

最后在main.js中:

代码语言:javascript
复制
$(function () {

    $.fn.changeBackgroundOnClick = function () {

        var target = this[0];
        var image = target.getAttribute('data-src');

        $(target).on('click', function(e) {

            // If JS is enabled, the click will prevent the browser from navigating to the image.
            e.preventDefault();

            $('#page').css({
                'background-image' : 'url(' + image + ')',
                'background-size' : 'cover',
                'background-repeat' : 'no-repeat'
            });
        });

        return this;
    }

    // We can now iterate over every element with data-background-change to give it the functionality you need. No code needs to be repeated. :)
    $('a[data-background-change]').each(function () {
        $(this).changeBackgroundOnClick(); 
    });

});

祝好运。

看看这把小提琴:http://jsfiddle.net/Nyyby/31/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26395057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档