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