【问题标题】:How to change background image with the help of querySelector如何在 querySelector 的帮助下更改背景图像
【发布时间】:2014-06-10 14:26:00
【问题描述】:

我只是想知道如何在使用查询选择器后设置 div 块的背景图像。下面是我的测试。但是这些都不起作用.......请帮忙。

<!DOCTYPE html>
<html>
<body>
<div class="A">
<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">Set background image</button>


</div>
</body>
</html>
<script>
function myFunction()
{
document.querySelector(".A").style.background="yellow"; //work
document.querySelector(".A").style.setProperty("backgroundImage", "url('2.jpg')")// not work
document.querySelector(".A").style.backgroundImage = "url('2.jpg')" //not work
}
</script>

【问题讨论】:

  • 最后(第三次)尝试看起来是正确的...您确定图像 2.jpg 存在并且与 HTML 文件位于同一目录中吗?跨度>
  • 你反对使用jQuery吗?

标签: javascript css html jquery-selectors background-image


【解决方案1】:
document.querySelector(".A").style.background="url('2.jpg')"; 

我对该代码进行了全面测试,它可以工作。

【讨论】:

    【解决方案2】:

    这里是a jsFiddle,可能会对您有所帮助。

    有许多用于编写样式的语法,这些语法很愚蠢且令人困惑。 backgroundImage vs background-image : vs background-image, vs backgroundImage =&gt; 急……傻。

    为了保持一致性,我总是使用下面的数组版本。

    我也使用 jQuery,因为它解决了跨浏览器问题并且更容易编写。

    document.querySelector(".your-selector").style.background="yellow";
    那么与
    $('.your-selector').css('background', yellow');


    HTML

    <button class="thing01">Set background image01</button>
    
    <button class="thing02">Set background image02</button>
    


    CSS

    body {
        background: gray;
    }
    


    jQuery

    // on document ready... 
    
    // for just one property... 
    $('body').css('background', 'url(http://placehold.it/400x400/00ff66)');
    
    /* This is syntax for multiple properties... note the comma on all but last and : vs , 
    $('body').css({
        'background'       : 'url(http://placehold.it/400x400/00ff66)',
        'background-size'  : 'cover'
    });
    */
    
    $('.thing01').on('click', function() {
        $('body').css({
            'background' : 'url(http://placehold.it/400x400/ff0066)'
        });    
    });
    
    $('.thing02').on('click', function() {
        $('body').css({
            'background' : 'url(http://placehold.it/400x400/6600ff)'
        });    
    });
    

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      相关资源
      最近更新 更多