图像翻转脚本未按预期工作

Image roll over script not working as expected

本文关键字:工作 翻转 脚本 图像      更新时间:2023-09-26

这就是我在HTML页面中调用JavaScript函数的方式:-

<script type="text/javascript" src="imagerollover.js"></script>
</script>
<script type="text/javascript">
//Following function should be called at the end of the page:
imagerollover();
</script>
</head>
<body>
.
.
.

这是我的imagerollover.js:-

function imagerollover(){
    
    var allimages=document.getElementsByTagName("img")
    var preloadimages=[]
    for (var i=0; i<allimages.length; i++){
        if (allimages[i].getAttribute("data-over")){ //if image carries "data-over" attribute
            preloadimages.push(new Image()) //preload "over" image
            preloadimages[preloadimages.length-1].src=allimages[i].getAttribute("data-over")
            allimages[i].onmouseover=function(){
                this.src=this.getAttribute("data-over")
            }
            allimages[i].onmouseout=function(){
                this.src=this.getAttribute("data-out")
            }
        } //end if
    } //end for loop
}
//Usage: Call following function at the end of the page:
//imagerollover()

图像标签:

<img src="knitting1.jpg" 
data-over="knitting2.jpg" 
data-out="knitting1.jpg" 
alt="Logo" width="400px" height="90" align="middle" />

此外,图像kniting1.jpg和kniting2.jpg都存在于我网站的根文件夹中。我不知道怎么了。

一开始我在imagerollover.js文件中放置了一个警告。它正在被调用,但没有显示出任何翻转效果。为什么?

你需要运行这个onload-当你执行函数时,你的图像标签还不能用于脚本-你实际上没有遵循脚本的指示,而脚本应该放在页面的末尾,或者我在onload 中的建议

<head>
<script type="text/javascript" src="imagerollover.js"></script>
</script>
<script type="text/javascript">
window.onload=function() 
  //Following function should be called at the end of the page OR on window.onload!
  imagerollover();
}
</script>
</head>