我运行了一个提供可平铺/无缝图案的免费资源站点,我正在尝试在我的帖子中添加一个按钮(带有脚本),访问者可以点击这个按钮来更改页面的背景图像,以便他们可以预览运行中的图案。例如,在这篇文章(http://tileablepatterns.com/denim-pattern/)上,我希望用户能够点击一个按钮/链接,它会将背景图像从灰色背景更改为牛仔图案。
我该怎么做呢?此外,最好是我希望它是一个简单的脚本,我可以只插入到帖子中,而不是必须编辑主题文件。
非常感谢您的帮助!
发布于 2014-10-16 10:10:35
给你的按钮一个ID,例如: id=" button“,然后下面的代码就会起作用:
$('#button').click(function(){ $('body').css('background', 'url(http://tileablepatterns.com/wp-content/uploads/2014/09/Denim.jpg) repeat 0 0'); });发布于 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>
它在现有背景中添加了两条白线,一条靠近顶部,一条靠近底部,但它不会改变整个背景。我认为有一个包装器覆盖在背景上,但我不知道如何更改代码,使其改变整个页面的背景,包括包装器?
发布于 2014-10-16 11:10:58
如果我要使用jQuery来做这件事,我会采用一种模块化的方法,这种方法很容易在HTML中模板化,并且在Javascript失败的情况下仍然有效。
从一些基本标记开始(我使用Baconmockup作为示例图像):
<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:
// 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中:
$(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/
https://stackoverflow.com/questions/26395057
复制相似问题