如何使用 "this" 更改 javascript 中的图像源?

How can I change image source in javascript using "this"?

我有一个 div 元素,其 id = "image" 最初没有背景图像。 我有另一个图像,当我将鼠标悬停在该图像上时,会调用 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 内联 styles/attributes;

中缺少一些 ""

此外,在 javaScript 函数中使用 backgroundImage + variable/string 连接。并在 #image div.

上添加默认 background-image css 样式

在javaScript中命名functions/variables时也使用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"/>