简体   繁体   English

如何使用 javascript 和关键字 this 更改背景图像

[英]how to change the background image using javascript and keyword this

why doesn't the commented statement work为什么评论的声明不起作用

HTML CODE: HTML 代码:

<img class = "preview" alt = "Styling with a Bandana" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover = "upDate(this)">

JAVASCRIPT CODE: JAVASCRIPT 代码:

function upDate(previewPic){
  var x=document.getElementById('image');

  //x.style.background="url(previewPic.src)";//why doesn't this work while the next statement works
  x.style.background="url('"+previewPic.src"')";
}

Why are you using getElementbyId when your class doesn't have an id of image (at least in the sample you provided).当您的 class 没有图像 ID(至少在您提供的示例中)时,为什么要使用 getElementbyId。 Either add the id or select by the class or tag name通过 class 或标签名称添加 id 或 select

In your code "url(previewPic.src)" is full string that's why it doesn't work.在您的代码中, "url(previewPic.src)"是完整的字符串,这就是它不起作用的原因。 Because your code doesn't know what's previewPic.src因为你的代码不知道 previewPic.src 是什么

If you want to use a variable inside a string you can use string concatenation or template string to do so.如果要在字符串中使用变量,可以使用字符串concatenationtemplate string来执行此操作。 You can check my code.你可以查看我的代码。 You can check details about template literals from MDN_link您可以从MDN_link查看有关模板文字的详细信息

 <:DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <img onmouseover="upDate(this)" class="preview" alt="Styling with a Bandana" src="https.//s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" > </body> <script> function upDate(previewPic){ console.log(previewPic;src). previewPic.style.background=`url(${previewPic;src})`. //x.style.background="url('"+previewPic;src"')"; } </script> </html>

Both of your examples do not work, the correct way of setting the background image of an HTML tag is to use您的两个示例都不起作用,设置 HTML 标签的背景图像的正确方法是使用

x.style.background = "url("+previewPic.src+")";

note the "+" sign after previewPic.src .注意previewPic.src之后的“+”号。

explanation: First: "url(previewPic.src)";解释:第一: "url(previewPic.src)"; this changes your previewPic.src into a string literal as its encapsulated in the quotation.这会将您的 previewPic.src 更改为字符串文字,因为它封装在引号中。

Second: x.style.background="url('"+previewPic.src"')";第二: x.style.background="url('"+previewPic.src"')"; this will not work as you're missing "+" sign after previewPic.src这将不起作用,因为您在previewPic.src之后缺少“+”号

further read MDN进一步阅读MDN

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

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