在onmouseover时更改背景图像

时间:2018-01-29 05:29:33

标签: javascript css html5

function change(ele) {
  document.getElementById('info').innerHTML = ele.alt;
  document.getElementById('info').style.backgroundImage = "url(ele.src)";
}
<div id='info'>
  This will tell you more about the below image
</div>
<div id='container'>
  <div>
    <img alt="The mini Barbarian" src="img\barbarian-thumb.jpg" class="pics" onmouseover="change(this)">
  </div>
</div>

如何使用id信息更改div的背景图像,鼠标悬停该图像的图像位于带有id conatiner的div标签中

4 个答案:

答案 0 :(得分:3)

请看这个。基本上你可以用html绑定函数内联。或者您可以动态绑定它。这是非常简单的解决方案。如果你的图像路径是固定的。

<script type="text/javascript">
function mouseaway(my_image) {
    my_image.src = "someimage.jpg";
}

function rollover(my_image) {
    my_image.src = "someimage2.jpg";
}
</script>

<img src="someimage3.jpg" onmouseover="rollover(this)" onmouseout="mouseaway(this)" />

答案 1 :(得分:0)

只需为您的图片代码指定一个ID,然后像这样更改图像src。

function mouseOverImage() {
  document.getElementById("img").src = "images/foo.png";
}

<img  
  id="img" 
  alt="some description/info"
  src="images/blue.png" 
  onmouseover = "mouseOverImage()"
/> 

答案 2 :(得分:0)

希望这会有所帮助

 $(document).ready(function(){
       $("img").hover(function(){
            $(this).attr('src', 'images/alt/imagename.jpg');
       });
    });

答案 3 :(得分:0)

试试这个:

function change(e){
  document.getElementById("info").style.backgroundImage = "url('"+e.src+"')";
  document.getElementById("info").style.backgroundRepeat="no-repeat";
}
function change2(e){
  document.getElementById("info").style.backgroundImage = "";
}
#info{
height:100px;
}
<div id='info'>
     This will tell you more about the below image
     </div>
 <div id='container'>
     <div>
      <img alt="The mini Barbarian" src = "data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2264%22%20height%3D%2264%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_1614068cdea%20text%20%7B%20fill%3Argba(255%2C255%2C255%2C.75)%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_1614068cdea%22%3E%3Crect%20width%3D%2264%22%20height%3D%2264%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2213.84375%22%20y%3D%2236.5%22%3E64x64%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" class="pics" onmouseover="change(this)" onmouseout="change2(this)">
     </div>
 </div>