[英]Change Element style with window height with JavaScript
I'm trying to change the background colour of a div element when the page window height is lower than a certain value using JavaScript. 当页面窗口高度低于使用JavaScript的某个值时,我试图更改div元素的背景颜色。 I have a vague idea of how this might work but it doesn't seem to be having any effect.
我对这可能如何工作有一个模糊的想法,但似乎没有任何效果。 This is within a tag and loads after the body of my HTML.
这是在标记内,并在HTML正文之后加载。
<script>
var footer = document.getElementByClassName("footer");
if (window.innerHeight < 800) {
footer.style.backgroundColor = 'black';
}
</script>
Like already mentioned getElementsByClassName
returns an array. 就像已经提到的,
getElementsByClassName
返回一个数组。 You had a typo there so nothing was returned, however. 您在那里打错了字,所以什么也没退。
As long as there's only 1 element with the class name "footer" this should work (might be better to use an ID): 只要只有1个元素的类名称为“页脚”,这应该可以工作(最好使用ID):
<script>
var footer = document.getElementsByClassName("footer")[0];
if (window.innerHeight < 800) {
footer.style.backgroundColor = 'black';
}
</script>
But yeah, you should really look at the dev console when you're writing Javascript. 但是,是的,在编写Javascript时,您应该真正看一下开发控制台。 It can save a lot of headaches!
它可以节省很多麻烦!
JavaScript does not have a method called getElementByClassName
. JavaScript没有名为
getElementByClassName
的方法。
The closest thing is getElementsByClassName
which returns an HTMLCollection
which is an array-like object, so to get the first element in the list you have use an index: 最接近的是
getElementsByClassName
,它返回一个HTMLCollection
,它是一个类似于数组的对象,因此,要使用索引来获取列表中的第一个元素:
var footer = document.getElementsByClassName('footer')[0];
You can also use querySelector
to get the first element with the class name: 您还可以使用
querySelector
获取具有类名称的第一个元素:
var footer = document.querySelector('.footer');
Here is a working example: 这是一个工作示例:
var footer = document.getElementsByClassName('footer')[0]; window.onresize = function (event) { if (window.innerHeight < 800) { footer.style.backgroundColor = 'black'; } else { footer.style.backgroundColor = 'blue'; } }
.footer { height: 50px; width: 100%; background: black; }
<footer class="footer"></footer>
JSFiddle Demo http://jsfiddle.net/moogs/x63rc6v4/1/ JSFiddle演示http://jsfiddle.net/moogs/x63rc6v4/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.