图像切换与纯JavaScript

时间:2016-05-11 18:38:44

标签: javascript html mouseout

所以我试图用javascript进行鼠标悬停以便图像不会真正显示为seo我首先在html中设置它以使css正确并且使所有内容都显示在document.write中所以它可以使用javascript生成(我的js知识是有限的)。所以使用html我正在制作

<img src="img/brokenarrowwear-googleplus.png" onmouseover="this.src='img/brokenarrowwear-google-circle.png';" onmouseout="this.src='img/brokenarrowwear-googleplus.png';"/>

但由于它使用“”和“它”并不真正起作用。我尝试过这样做

document.write(' <img src="img/brokenarrowwear-googleplus.png" onmouseover="this.src=' + 'img/brokenarrowwear-google-circle.png' + ';" onmouseout="this.src=' + 'img/brokenarrowwear-googleplus.png' + ';"/> ')

但这也没有用。有谁知道我怎么能做纯JavaScript?我找到了

$("img.image-1").mouseenter(function () {
    $(this).replaceWith($('<img src="~/Content/images/prosecutor_tile_b.jpg">'));
});

但我认为它不会起作用。

3 个答案:

答案 0 :(得分:0)

简单的内联纯Javascript解决方案:

<script>
           document.write("<img src=\"http://placehold.it/150x150?text=image1\"   onmouseover=\"this.src='http://placehold.it/150x150?text=image2'\"  onmouseout=\"this.src='http://placehold.it/150x150?text=image1'\" />");     
</script>

文字说“image1”,鼠标悬停时图片中的文字会显示“image2”

答案 1 :(得分:0)

也许这会有所帮助:

<img id="mypic" src="img/brokenarrowwear-googleplus.png"  onmouseover='pictureChange(true)' onmouseout='pictureChange(false)'>

功能图片更改:

function pictureChange(change){
    If(change==true){
        document.getElementById("mypic").src="img/brokenarrowwear-googleplus.png";
    }else{
    document.getElementById("mypic").src="img/brokenarrowwear-google-circle.png";
    }
}

答案 2 :(得分:0)

问题不在于脚本。我在脚本源中看到它,但我没有在渲染的html中看到它,实际上整个img标签都丢失了。含义您遇到某种类型的渲染问题或删除了其他脚本。

让我们看看它是否与内联javascript相关并且使用反斜杠转义不起作用:从google img中删除onmouseover和onmouseout属性,给它一个id =“googlelogo”并在你的结尾添加以下脚本体:

<script>
document.getElementById("googlelogo").onmouseover = function() {
    this.src = "img/brokenarrowwear-google-circle.png";
  }
document.getElementById("googlelogo") .onmouseout = function() {
    this.src = "img/brokenarrowwear-googleplus.png";
  }
</script>