【问题标题】:Setting background-color in div is not working在 div 中设置背景颜色不起作用
【发布时间】:2017-12-20 01:17:35
【问题描述】:

我在这里有点问题。我正在尝试设置<div id='coupons'> 的背景颜色,但是当我这样做时,什么都没有发生!请帮我解决这个问题。我留下了大部分 CSS,因为我没有任何冲突的背景颜色标签。

#coupons {
  background-color: black;
}
<div id='coupons'>
  <a id="coupons" name='coupons'>
    <div style="float:left">
      <img id='myImg' src="https://preview.ibb.co/jBYUxv/coupon1.png" id="i1" height="300px" width="600px">
      <div id="myModal" class="modal">
        <span class="close">×
    		  </span>
        <img class="modal-content" id="img01">
        <div id="caption">
        </div>
        <script>
          // Get the modal
          var modal = document.getElementById('myModal');
          // Get the image and insert it inside the modal - use its "alt" text as a caption
          var img = document.getElementById('myImg');
          var modalImg = document.getElementById("img01");
          img.onclick = function() {
            modal.style.display = "block";
            modalImg.src = this.src;
          }
          // Get the <span> element that closes the modal
          var span = document.getElementsByClassName("close")[0];
          // When the user clicks on <span> (x), close the modal
          span.onclick = function() {
            modal.style.display = "none";
          }
        </script>
      </div>
    </div>
    <div id='pformat'>
      <p>COUPONS FOR YOU!
      </p>
    </div>
  </a>
</div>

【问题讨论】:

  • 我看到图片后面有黑色背景。

标签: javascript html css background-color


【解决方案1】:

#coupon 中的 div 是浮动的,这意味着 #coupons colappses... 意味着它没有高度,因此没有背景。试试这个... #coupons:after { content: "";显示:表格;明确:两者; } 来清除它的浮动子节点。

【讨论】:

  • 嘿,我再次遇到了类似的问题,但是当我将此解决方案应用于此问题时。它没有用。相同的 css 但 html 是这样的:
【解决方案2】:

您的 .png 似乎不透明。图像本身具有白色背景。

ID #coupons 被多次使用,也许这会产生不想要的结果。

【讨论】:

    【解决方案3】:

    正如@Barmar 所说,我可以看到图像后面的黑色,所以我假设您正在寻找jQuery 解决方案。

    [此外,@Joe B. 对你的 png 的透明度提出了一个有效的观点]

    如果您尝试使用jQuery 更改背景颜色,您可以使用.css()

    $('#coupons').css(`background-color`, 'pink');
    #coupons {
      background-color: black;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="coupons">I am a coupons</div>

    【讨论】:

    • 由于某种原因,我看不到图像后面的黑色。我不确定为什么。我认为这一定与我的显示器尺寸有关。
    • @K.Patel - FWIW,我倾向于将需要保持一定填充的元素包装起来,并且可能会在“容器”div 中随视框而改变(或不改变)。如&lt;div class="coupon_container"&gt;&lt;div id="coupons"&gt;"other stuff"&lt;div/&gt;&lt;div/&gt;。此外,虽然您的代码可以使用重复的元素 ID,但尽量不要使用相同的 ID 两次(您的 &lt;a&gt; 标签。)类对于将通用样式应用于多个元素要有效得多,并且 jq 逻辑也不会更难进行个人选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2014-07-20
    • 2018-06-11
    相关资源
    最近更新 更多