javascript - 如果存在子 div,则使用 javascript 更改背景

标签 javascript css if-statement joomla

当存在子 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>

如有任何帮助,我们将不胜感激。谢谢!

最佳答案

给定 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>

只需确保在元素呈现到页面后列出它,否则您将需要将上面的内容绑定(bind)到 DOMReady 事件。

关于javascript - 如果存在子 div,则使用 javascript 更改背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13501273/

相关文章:

javascript - 我可以将 ReactJS Native 的值分配给 Swift 全局变量吗?如果是这样,如何?

javascript - 如何捕获用户意外离开 ASP.Net 页面的情况

html - 如何将 CSS 和样式应用于 React 组件

mysql - 如何在 Node mysql 中使用 IF EXISTS 语句?

swift - 如何在 swift 中使用 guard 而不是 if

swift - Swift 中 if 语句和循环的所有括号都是可选的吗?

javascript - 为什么我需要将单词 this 添加到我的 javascript 方法中

Javascript 模运算给出错误的结果

javascript - 制作视频作为我的网站图标播放

html - 如何防止无序列表中列表元素的边界重叠