当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - jQuery - replacing div background image from URL

问题描述:

I'm trying to replace div background in several divs from label element (typed URL) and while the code works, it won't push through $('#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>

Basically I need whatever is typed to be loaded as a background image.

Thanks for any suggestions.

网友答案:

let try

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

Wrap your Dom elements inside a div and iterate through it looking for div elements and add background-image css property to each div with urlImage input's value This would only work if you already have some value in your input element in order to handle it always you should handle it through keypress or keyup event

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
     });
     })

Edit 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
       });
       });
       })
分享给朋友:
您可能感兴趣的文章:
随机阅读: