当标题更改大小时,我想为其创建一个函数。
我在标头中有一个徽标img。我想在更改标头s height to be for example 80px the image to be 80 px as well.
I initialized a function in Javascript but doesn
不起作用时使用(我是Java语言的初学者)。请告诉我我在JS中做错了什么,也许告诉我正确的方法。
<header class="header">
<div class="container">
<div class="header-content">
<img src='http://www.lazarangelov.com/wp-content/uploads/2015/12/logo1.jpg' class="logo" alt="logo">
<div class="menu-links">
<ul class="links-list">
<li><a href="#">Home</a></li>
<li><a href="#">Bio</a></li>
<li><a href="#">Training</a></li>
<li><a href="#">Academy</a></li>
<li><a href="#">Gallery</a></li>
<li><a href="#">Store</a></li>
<li><a href="#">Contacts</a></li>
</ul>
</div>
</div>
</div>
</header>
.header {
background: blue;
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 20;
height: 80px;}
.header-content{
display:flex;
}
.menu-links{
display:flex;
}
.links-list{
display:flex;
color:white;
}
const mainNav = document.querySelector('.header');
const img = document.querySelector('.logo');
if (mainNav.style.height == '80px') {
img.style.height = '80px';
} else {
img.style.height = '100px';
}
答案 0 :(得分:1)
<div>
<input matInput placeholder="test" autocomplete="off">
</div>
属性只能返回直接在HTML元素中设置的样式信息,这些信息可以在HTML中像.style
一样静态地或通过在JavaScript中设置的<p style="something here">
来返回。如.style
。您的代码基于检查element.style = something;
的{{1}}条件,但是此时尚未在HTML或JavaScript中设置if
属性。
相反,请使用.getComputedStyle()
,它会在考虑所有计算(无论应用了什么位置)之后返回所提供样式的最终值。
我在下面的代码中为您的图像添加了一个红色边框,以表明该图像正在将mainNav.style.height
扩展为与style
相同的大小。
height
header
const mainNav = document.querySelector('.header');
const img = document.querySelector('.logo');
// You can't check the .style property if the element
// hasn't had that attribute or property set yet.
if (getComputedStyle(mainNav).height == '80px') {
img.style.height = '80px';
} else {
img.style.height = '100px';
}
答案 1 :(得分:0)
Javascript中的style属性仅为您提供元素的内联样式-直接在其上的style
属性中定义的样式。
您需要getComputedStyle来访问使用的实际属性,并考虑所有CSS规则。