2

当子 div (ezblog-head) 存在时,我需要更改父 div (content-indent) 的背景图像。我在网上找到了很多答案。但我似乎无法让他们中的任何一个工作。

实际的 index.php 页面如下所示:(该站点是使用 Joomla 构建的)

<div class="content-indent">
    <jdoc:include type="component" />
</div>

在浏览器中加载为:

<div class="content-indent">
    <!-- bunch of other stuff -->
    <div id="ezblog-head>
        <!-- more stuff -->
    </div>
</div>

这是我在索引页面上使用的 Javascript(它不起作用)

<script type="text/javascript">
    if ($('#ezblog-head')[0]){
      <style>
       .content-indent {background: #0f0;}
      </style>
    }
</script>`

我也试过这个(无济于事):

<script type="text/javascript">
    if (document.getElementById("ezblog-head")) { 
        document.getElementByClass('content-indent').style.background ='#0f0'
    }
</script>

任何帮助将不胜感激。谢谢!

4

3 回答 3

0

不要使用样式标签,而是使用 jQuery .css()。请注意,这是使用 jQuery 而不是纯 javascript,因此您还必须在此脚本块之前引用 jQuery。

if ($('#ezblog-head')) {
     $('.content-indent').css({'background': '#0f0'});
}
于 2012-11-21T20:22:37.910 回答
0

给定ezblog-head一个 ID(假设页面中只有一个),您可以使用:

<script type="text/javascript">
var ezblogHead = document.getElementById('ezblog-head');
if (ezblogHead){
    // ezblog-head exists on the page. Now, grab it's parent (content-indent)
    // and apply the bakground styling you prefer.
    ezblogHead.parentNode.style.backgroundColor = '#0f0';
    // alternatively, if you wanted an image:
    //ezblogHead.parentNode.style.backgroundImage = 'url(/path/to/background.jpg)';
}
</script>

Just make sure this is listed after the element has been rendered to the page, otherwise you're going to need to get in to binding the above to a DOMReady event.

于 2012-11-21T20:22:44.383 回答
0

Your last sans-jquery example is almost there, but you'd want to use getElementsByClassName('content-indent')[0] (note the plural nature)

Easier still would be to use querySelector:

// change background of parent div (content-indent) when child div (ezblog-head) is present
if (document.querySelector('#ezblog-head')) {
  document.querySelector('.content-indent').style.backgroundColor = '#0f0';
}

As noted elsewhere, make sure you're running the code after the dom is loaded, ie:

window.addEventListener('load', function() {
  // do stuff here, the DOM is ready
});
于 2012-11-21T20:26:51.653 回答