在学校里,他们只教如何应用 javascript 来更改我们网页主体的 bgcolor。我希望当我将鼠标悬停在按钮或 div 内容上时,div 的背景图像应该自动更改。我的代码中缺少什么?
HTML:
<!DOCTYPE html>
<html>
<body>
<center>
<input type="button" name="b1" value="Change Image" onmouseover="f1()">
<script src="javascript1.js">
</script>
<br><br>
<div id="main">
<h1>Karan</h1>
<h1>Karan</h1>
</div>
</body>
</html>
JavaScript :
function f1()
{
document.getElementById(main).style.backgroundImage = "url('https://upload.wikimedia.org/wikipedia/commons/7/7c/Aspect_ratio_16_9_example.jpg')";
window.setTimeout("f2()",1200);
}
function f2()
{
document.getElementById(main).style.backgroundImage = "url('http://gallery.onderhond.com/galleries/2009/santorini-towns/08.JPG')";
window.setTimeout("f3()",1200);
}
function f3()
{
document.getElementById(main).style.backgroundImage = "url('https://upload.wikimedia.org/wikipedia/commons/7/7c/Aspect_ratio_16_9_example.jpg')";
window.setTimeout("f4()",1200);}
function f4()
{
document.getElementById(main).style.backgroundImage = "url('http://gallery.onderhond.com/galleries/2009/santorini-towns/08.JPG')";
window.setTimeout("f5()",1200);
}
function f5()
{
document.getElementById(main).style.backgroundImage = "url('https://upload.wikimedia.org/wikipedia/commons/7/7c/Aspect_ratio_16_9_example.jpg')";
window.setTimeout("f6()",1200);}
function f6()
{
document.getElementById(main).style.backgroundImage = "url('http://gallery.onderhond.com/galleries/2009/santorini-towns/08.JPG')";
window.setTimeout("f7()",1200);
}
function f7()
{
document.getElementById(main).style.backgroundImage = "url('https://upload.wikimedia.org/wikipedia/commons/7/7c/Aspect_ratio_16_9_example.jpg')";
window.setTimeout("f1()",1200);
}
最佳答案
您需要使 main
成为传递给 document.getElementById()
的字符串。
例如:
document.getElementById("main")
此外,我会调用 setInterval
,或者我会递归地使用 setTimeout
并为您的回调函数提供一个参数,该函数会跟踪您所处的时间间隔...... . 你现在构建它的方式有点困惑,基本上看起来你所有的函数都会在 1200 毫秒后立即调用,而不是得到你正在寻找的顺序。
例如:
function change_image(num) {
switch(num) {
case 0:
document.getElementById("main").style.backgroundImage = /* something */
break;
case 1:
document.getElementById("main").style.backgroundImage = /* something else */
break;
case 2:
document.getElementById("main").style.backgroundImage = /* something else */
break;
/* cases 3-6 */
};
//this will cause num to repeat from 0-6
setTimeout(change_image, 1200, (num + 1) % 7);
}
//make the initial call
setTimeout(change_image, 1200, 0);
关于javascript - 我希望 div 的背景图片应该自动更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32073505/