【问题标题】:Setting background image using javascript without hard-coding使用 javascript 设置背景图像,无需硬编码
【发布时间】:2020-05-27 14:06:07
【问题描述】:

在这里,我试图通过使用 javascript 函数对每个图像进行硬编码,将这些图像显示为 id 为“消息”的 div 部分的鼠标悬停事件的背景图像,如下所示。

正文部分的 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 show1()
{ 
  document.getElementById('message').style.backgroundImage = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg')"
}

有什么方法可以使用 src 属性使用 javascript 更改它,而无需对 url 进行硬编码并动态更改它?

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    看看这是不是你想要的:

    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">

    已编辑

    【讨论】:

    • 想要将图像设置为 id 为“消息”的 div 部分的背景。此代码正在附加图像。
    • 在我的示例中,我让 div.#message 接收图像的宽度和高度只是为了演示,但如果您已经有了 div。 # 消息的高度和宽度由 css 预先定义,只需删除以下行: message .style.width = this.width + 'px' 和 message.style.height = this.height + 'px'
    • 有没有不使用jquery的方法?
    • 我做的方式我没有使用jquery,这是javascript。执行代码时遇到问题?
    猜你喜欢
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多