【问题标题】:Set background image in CSS using jquery [duplicate]使用jquery在CSS中设置背景图像[重复]
【发布时间】:2013-12-19 10:55:35
【问题描述】:

我正在尝试使用 jquery 为我的一个 html 元素设置背景图像

<div class="rmz-srchbg">
    <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
    <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
    <br style="clear:both;">
</div>

$("#globalsearchstr").focus(function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat;");
});

但这永远不会奏效。唯一的改变是在 HTML 中添加了一个样式属性,就像这样

<div class="rmz-srchbg" style="">

</div>

CSS 没有变化。

【问题讨论】:

  • 使用绝对路径怎么样?如果您的相对路径准确,请在控制台中检查
  • CSS $(this).css('background-image', 'url(' + imageUrl + ') no-repeat');
  • 这不起作用 background-image 是错误的,它应该是 backgroundImage

标签: javascript jquery html css


【解决方案1】:

试试这个:

<div class="rmz-srchbg">
    <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
    <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
    <br style="clear:both;">
</div>
<script>
$(function(){
   $('#globalsearchstr').on('focus mouseenter', function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
   });
});
</script>

【讨论】:

    【解决方案2】:

    使用:

     $(this).parent().css("background-image", "url(/images/r-srchbg_white.png) no-repeat;");
    

    而不是

     $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat;");
    

    更多例子你可以看到here

    【讨论】:

    【解决方案3】:

    试试这个

     $(this).parent().css("backgroundImage", "url('../images/r-srchbg_white.png') no-repeat");
    

    【讨论】:

    • 感谢分享。在url() 中为'' +1。这就像一个魅力。
    【解决方案4】:

    试试这个

    $("#globalsearchstr").focus(function(){
        $(this).parent().css("background", "url('../images/r-srchbg_white.png') no-repeat");
    });
    

    【讨论】:

    • 不工作。还是同样的问题(有问题解释)
    • @Athul 现在试试,有什么错误?
    【解决方案5】:

    去掉网址中no-repeat后的分号,试试看。

    $("#globalsearchstr").focus(function(){
        $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
    });
    

    【讨论】:

    • “背景”属性不正确。你想说的“背景图片”。
    【解决方案6】:

    你必须删除css规则字符串中的分号:

    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
    

    【讨论】:

      【解决方案7】:
      <div class="rmz-srchbg">
        <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
        <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
        <br style="clear:both;">
      </div>
      
      $(document).ready(function() {
        $('#globalsearchstr').bind('mouseenter', function() {
          $(this).parent().css("background", "black");
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-05
        • 2021-03-14
        • 1970-01-01
        • 1970-01-01
        • 2013-01-15
        • 1970-01-01
        • 2016-09-01
        相关资源
        最近更新 更多