【问题标题】:jQuery - replacing div background image from URLjQuery - 从 URL 替换 div 背景图像
【发布时间】:2016-06-11 08:27:52
【问题描述】:

我正在尝试从标签元素(键入的 URL)替换几个 div 中的 div 背景,虽然代码有效,但它不会通过 $('#urlImage')

jQuery:

$(document).ready(function(){
$('.first, .second, .third').append("");
  $('#urlImage').change(function(){
    $('.first, .second, .third').css('background-image', $('#urlImage').val());
  });
})

HTML

<input type="text" id="urlImage" placeholder="Type image URL">

<div class="first">
</div>
<div class="second">
</div>
<div class="third">
</div>

基本上,我需要将输入的任何内容加载为背景图像。

感谢您的任何建议。

【问题讨论】:

  • 通过检查元素来检查css是否被正确应用,哦,它的jQuery不是jQuary
  • css 一切都很好,我可以放置其他东西,只是不能以那种形式放置背景图像(样式)。大声笑,已编辑,谢谢!

标签: javascript html image url background


【解决方案1】:

试一试

$(document).ready(function(){
  $('#urlImage>div').each(function(){
    $(this).css('background-image', $('#urlImage').val());
  });
})

【讨论】:

  • 我的想法,在边 id="urlImage" 中查找所有 div。对于每个 div,您将更改背景图像。
  • 但这会改变#urlImage 中的div,我需要单独更改它们。谢谢回复!
  • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性的 cmets 挤满你的代码,这会降低代码和解释的可读性!
  • @BydenProps:当然可以。在这个时候,我的解决方案是变通。请投票给我。
【解决方案2】:

将您的 Dom 元素包装在一个 div 中并遍历它以查找 div 元素并使用 urlImage 输入的值将 background-image css 属性添加到每个 div 这只有在您的输入元素中已经有一些值以便始终处理它时才有效,您应该通过 keypress 或 keyup 事件处理它

HTML

      <div id="wrapper">
      <input type="text" id="urlImage" placeholder="Type image URL">

       <div class="first">
       </div>
        <div class="second">
         </div>
         <div class="third">
        </div>
       </div>

JS:

     $(document).ready(function(){
     var imageUrl = document.getElementById("#urlImage").value;
    $('#wrapper > div').each(function () {
      this.css('background-image', 'url(' + imageUrl + ')');// "this" is the current element in the loop
     });
     })

编辑 1

    (function(){
      $( "#urlImage" ).keyup(function(){
        var imageUrl = document.getElementById("#urlImage").value;
       $('#wrapper > div').each(function () {
        this.css('background-image', 'url(' + imageUrl + ')');// "this" is the current element in the loop
       });
       });
       })

【讨论】:

  • 谢谢,这似乎可行,但我收到错误:未捕获的 TypeError: document.getElementbyId is not a function
  • 我已经编辑了答案,请看一下。这是一个错字,应该是 document.getElementById 而不是 document.getElementbyId
  • 好的,错字已修复,现在我有:未捕获的类型错误:无法读取 null 的属性“值”
猜你喜欢
  • 2018-05-01
  • 2010-09-20
  • 1970-01-01
  • 2017-08-31
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多