我的 jQuery:
$(document).ready(function() {
$('.display').mouseenter(function() {
$(this).fadeTo('fast',0);
});
$('.display').mouseleave(function() {
$(this).fadeTo('fast',1);
});
});
我的 CSS:
div {
display:inline-block;
}
.display {
padding:10px;
}
.bluespot {
height:10px;
width:10px;
border-radius:100%;
background-color:blue;
}
.redspot {
height:10px;
width:10px;
border-radius:100%;
background-color:red;
}
我的 HTML:
<div>
<div class='display'><div class='bluespot'></div></div>
<div class='display'><div class='redspot'></div></div>
</div>
请看这里http://jsfiddle.net/andrewtanner/ZyEKz/1/
我想做的是重复这些红色和蓝色的 CSS 类作为背景,最好与用户屏幕相关。我可以通过简单地粘贴更多代码来一遍又一遍地重复这些类,但这似乎并不是特别有效,而且它只会达到一个绝对值。当它不是图像背景时,有什么方法可以重复 CSS,即 background-repeat 元素?
最佳答案
您可以做的是使用 javascript 动态添加您的“spots”div。这是主要思想:
- 你得到屏幕的宽度和高度
- 将它们除以一个点的宽度和高度
- 循环遍历高度上的点数
- 在此循环中,您再次使用宽度上的点数进行循环
也许用这个 Fiddle 观看它的效果更好
这是循环:
// spots are 30x30 squares
// how much can we put in height ?
number_h = parseInt(window_h / 30);
// in width
number_w = parseInt(window_w / 30);
for(var h_it = 0; h_it < number_h; h_it++)
{
for(var w_it = 0; w_it < number_w; w_it++)
{
// to make one blue, one red, one blue...
// and change the order the next line
if(w_it%2 === h_it%2) {
$('<div class="display"><div class="bluespot"></div></div>')
.appendTo('#container');
} else {
$('<div class="display"><div class="redspot"></div></div>')
.appendTo('#container');
}
}
}
当然这可能并不完美,但至少你明白了。
这是一个更复杂的 fiddle ,带有居中容器和在窗口调整大小事件时刷新:
http://jsfiddle.net/ZyEKz/10/
关于jquery - 尝试结合使用 CSS、jQuery 和 HTML 来创建可重复的 mouseenter/mouseleave 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17599603/