[英]Setting background image using javascript without hard-coding
Here I was trying to display these images as a background image on mouseover event for div section with id 'message' by hard-coding using javascript function for each image as follows.在这里,我试图通过对每个图像使用 javascript function 进行硬编码,将这些图像显示为 ID 为“消息”的 div 部分的鼠标悬停事件的背景图像,如下所示。
HTML code inside body section正文部分内的代码 HTML
<div id = "message">
Hover over an image to display the
alt text.
</div>
<img class = "preview"
alt = "Styling with a Bandana"
src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg"
onmouseover = "showProperties(this);show1()"
onmouseleave = "document.getElementById('message').innerHTML='Hover over an image'; show()">
<img class = "preview"
alt = "With My Boy"
src = "https://s3-us-west 2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG"
onmouseover = "showProperties(this);show2()"
onmouseleave = "document.getElementById('message').innerHTML='Hover over an image';show()">
<img class = "preview"
src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg”
alt = "Young Puppy"
onmouseover = "showProperties(this);show3()"
onmouseleave = "document.getElementById('message').innerHTML='Hover over an image';show()">
Javascript function for setting background image: Javascript function 用于设置背景图片:
function show1()
{
document.getElementById('message').style.backgroundImage = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg')"
}
Is there any way to change it using src attribute using javascript without hard-coding the url and change it dynamically?有没有办法使用 javascript 使用 src 属性更改它,而无需对 url 进行硬编码并动态更改它?
See if this is what you want:看看这是不是你想要的:
let previews = document.querySelectorAll('.preview') // get all div.preview for(let preview of previews) { // Creates the mouseover event for all div.preview preview.addEventListener('mouseover', function(e) { let message = document.querySelector('#message') message.style.background = `url(${this.src})` message.style.width = this.width + 'px' message.style.height = this.height + 'px' message.style.backgroundSize = 'contain' message.style.backgroundRepeat = 'no-repeat' }) }
<div id="message"> Image here </div> <img class="preview" width="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg"> <img class="preview" width="200" src="https://s3-us-west 2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG"> <img class="preview" width="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg">
Edited已编辑
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.