繁体   English   中英

如何使用“ this”更改javascript中的图片来源?

[英]How can I change image source in javascript using “this”?

我有一个id =“ image”的div元素,最初没有背景图像。 我有另一个图像,当我将鼠标悬停在其上时,将调用somefunction(this)。 现在,我希望此函数将div的背景图像更改为悬停的图像。 我正在做这样的事情...

HTML:

<div id = "image"> a division </div>
<img class = "abc" onmouseover = somefunction(this) src ="someimage.jpg>

CSS:

#image{ background-image : url(''); }

JS:

function somefunction(element)
{
    var x = document.getElementById('image');
    x.style.background.src = element.src;
}

但是无论如何它都不起作用,我只想使用“ this”来做到这一点。

试试这个代码

 function somefunction(element) { var x = document.getElementById('image'); x.style.backgroundImage = "url('"+element.src+"')" } 
  <div id = "image"> a division </div> <img class = "abc" onmouseover="somefunction(this);" src="your path to file.PNG"/> 

您的HTML内联样式/属性中缺少一些""

另外,在javaScript函数中使用backgroundImage +变量/字符串串联。 并在#image div上添加默认的background-image CSS样式。

在javaScript中命名函数/变量时,也请使用camelCase 因此somefunction应该是someFunction

 function someFunction(element) { var x = document.getElementById('image'); console.log() x.style.backgroundImage ='url('+element.src+')'; } 
 #image { height:100px; width:200px; background-image:none; background-size:cover; background-repeat:no-repeat; margin-bottom:15px; } 
 <div id = "image"> a division </div> <img class = "abc" onmouseover="someFunction(this)" src="https://via.placeholder.com/350x150"> 

 function somefunction(element){ var x = document.getElementById('image'); x.style.backgroundImage = "url('http://s9.tinypic.com/mb4bux_th.jpg')" console.log("div's background changed") } 
 <div id = "image"> a division </div> <img class = "abc" onmouseover = somefunction(this) src="http://s9.tinypic.com/2lv1yrt_th.jpg"/> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM