簡體   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