【问题标题】:Change div background-url by clicking通过单击更改 div background-url
【发布时间】:2013-12-24 13:41:29
【问题描述】:

所以,我得到了这个 div:

<div id="pictures" style="
position: absolute;
bottom: 0px; left: 0;
width: 100%;
background-image: url(inhalt/lan7071.jpg);
background-position: bottom;
 background-size: contain;
background-repeat: no-repeat;
z-index: 1;
height: -moz-calc(100% - 170px);
height: -webkit-calc(100% - 170px);
height: -o-calc(100% - 170px);"
></div>

在同一个 .htm 的其他地方单击表格中的文本我想更改此 div 的背景 url:

  <table>
    <tr>
      <td ><a onclick="document.getElementById('pictures').style.background='url(content/image2.jpg)'">Image 2<a></td>
      <td ><a onclick="document.getElementById('pictures').style.background='url(content/image3.jpg)'">Image3<a></td>

    </tr>
  </table>

点击“图片2”后,背景确实发生了变化,而且在整个div上也重复了,我猜是“ background-size: contains; background-repeat: no-repeat;”被忽略。

有没有什么小而简单的 jQuery 方法可以在单击另一个 div 后简单地更改另一个 div 的背景 URL?我还希望新背景保留早期的规范,如无重复、大小包含等......

我喜欢能够在每个链接之前或之后添加一个简短的 js 代码并在网站的其他地方拥有一个 js 函数的想法。

jsfiddle 在这里:http://jsfiddle.net/R7gEH/

非常感谢,圣诞快乐!

【问题讨论】:

    标签: html background repeat


    【解决方案1】:

    当您更改背景属性时,您会覆盖与背景相关的所有内容。只需设置背景图像。对于 javascript,它将是 backgroundImage

    使用 jquery

    $("#pictures").css("background-image", "new url");
    
    【解决方案2】:

    这样使用:

    ----CSS-----------

    .background-change{
        //set new property of image with !important 
    }
    

    --------jQuery --------

    $('a').click(function(){
        $(this).addClass('background-change') ;
    });
    

    这将添加新的属性类。不需要时也将其删除。(使用 removeClass() 函数)

    【讨论】:

    • 谢谢 Riad ...当我想要在 div 中显示大约 200 张图片时,这不是太复杂了吗?我为这个问题添加了一个 jfiddle:jsfiddle.net/R7gEH
    【解决方案3】:

    谢谢大家...我做了以下事情:

    http://jsfiddle.net/8m7VB/

    <div id="bilder" style="position: absolute; bottom: 0px; left: 0px; width: 100%;
    height: -moz-calc(100% - 170px); height: -webkit-calc(100% - 170px); height: -o-calc(100% - 170px);
    
    background: url(https://www.google.de/logos/doodles/2013/holiday-series-2013-2-5173241802915840-hp.png) center bottom no-repeat; background-size: contain; z-index: 1;"></div>
    <a onclick="document.getElementById('bilder').style.background='url(https://www.google.de/logos/doodles/2013/holiday-series-2013-2-5173241802915840-hp.png) center bottom no-repeat'">google<a>
    <a onclick="document.getElementById('bilder').style.background='url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9G
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 2014-04-04
      相关资源
      最近更新 更多