我在div中有一个列表,当我将鼠标悬停在列表项上时,我想更改父div (#homepage_container)的背景图像。
以下是该网站:
http://www.thebalancedbody.ca/
这个是可能的吗?我猜我将不得不使用javascript。
谢谢
乔纳森
发布于 2010-06-06 03:53:26
你必须使用JS。最好是学习像jQuery这样的东西。有了它,你必须做一些像这样的事情
var images = ['img1.jpg', 'img2.jpg', ...]
for (var i = 0; i < li_count; ++i) // li_count is the number of li's
$('li:eq(' + i + ')').mouseover(function() {$('#homepage_container').css('background-image', images[i]})无论如何,如果你想使用这样的技术,你必须学习JS。有关基础知识和jQuery的http://docs.jquery.com/Tutorials,请参阅http://www.w3schools.com/js/default.asp和。
发布于 2010-06-06 03:56:13
这对于纯javascript来说非常简单。
function changeBg(newBg)
{
var imgdiv = document.getElementById("divwithbackground");
imgdiv.style.backgroundImage = "url(" + newBg + ")";
}或者使用精灵:
imgdiv.style.backgroundPosition = "new position";在javascript中的事件注册可以用很多方法来完成,但是要在脚本中完成,我推荐使用QuirksMode的方法here。
类似于:
function addEventSimple(obj,evt,fn) {
if (obj.addEventListener)
obj.addEventListener(evt,fn,false);
else if (obj.attachEvent)
obj.attachEvent('on'+evt,fn);
}在加载时:
// get the list items
var ul = document.getElementById("ulId");
var lis = ul.getElementsByTagName("li");
// add event handlers
for (var i = 0; i < lis.length; i++)
{
addEventSimple(lis[i], "mouseover", (function(j) {
return function() {
// get your background image from the li somehow
changeBg(lis[j].id + "_bg.png");
};
})(i)); // use a closure to capture the current value of "i"
}发布于 2010-06-07 17:32:16
我建议为此安装Jquery库(jquery.com)
只需将以下内容添加到您的标题中:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
<script type="text/javascript">
$(document).ready(function() {
$('li').hover(function(){
$('#homepage_container').css('background-image' : 'whatever.png');
}
});
</script>https://stackoverflow.com/questions/2981828
复制相似问题