我有一个搜索栏,上面有一个切换按钮。当我单击切换按钮时,它会逐渐更改不透明度。它工作得很好,但是看起来有点笨拙,因为当我禁用它(从而隐藏元素)时,它会更改页面的大小。有禁用和隐藏元素的另一种方法吗?
Javascript:
function ToggleSearchBar() {
var searchbar = document.getElementById("SearchBar");
var display = getComputedStyle(searchbar).display;
if (display == "none") {
searchbar.style.opacity = 0;
searchbar.style.display = "block";
var i = 1;
function IncreaseOpacity() {
setTimeout(function() {
searchbar.style.opacity = i * .1;
i++;
if (i <= 10) {
IncreaseOpacity();
}
}, 30)
}
IncreaseOpacity();
} else {
var v = 10;
function DecreaseOpacity() {
setTimeout(function() {
searchbar.style.opacity = v * .1;
v--;
if (v >= 0) {
DecreaseOpacity();
} else {
searchbar.style.display = "none";
}
}, 30)
}
DecreaseOpacity();
}
}
<div class="search-button">
<p onclick="ToggleSearchBar()">Search</p>
<form id="SearchBar">
<input type="text" placeholder=" Your query here">
</form>
</div>
我尝试修改 disabled 属性,但是没有成功。如果您有任何建议,那就太好了。谢谢!
答案 0 :(得分:2)
我不知道您的CSS样式如何!但是为了防止页面大小改变,可以为父元素设置固定属性。例如,我给父类.search-button
设置了固定的高度,您可以通过递归来设置自己的高度
function ToggleSearchBar() {
var searchbar = document.getElementById("SearchBar");
var display = getComputedStyle(searchbar).display;
if (display == "none") {
searchbar.style.opacity = 0;
searchbar.style.display = "block";
var i = 1;
function IncreaseOpacity() {
setTimeout(function(){
searchbar.style.opacity = i * .1;
i++;
if (i <= 10) {
IncreaseOpacity();
}
}, 30)
}
IncreaseOpacity();
} else {
var v = 10;
function DecreaseOpacity() {
setTimeout(function(){
searchbar.style.opacity = v * .1;
v--;
if (v >= 0) {
DecreaseOpacity();
} else {
searchbar.style.display = "none";
}
}, 30)
}
DecreaseOpacity();
}
}
.search-button {
background :#eee;
padding:10px;
height:100px;
}
<div class = "search-button">
<p onclick = "ToggleSearchBar()">Search</p>
<form id = "SearchBar">
<input type = "text" placeholder = " Your query here">
</form>
</div>
答案 1 :(得分:2)
是否存在禁用和隐藏元素的另一种方法?
答案 2 :(得分:2)
我将您的display = "none"
更改为visibility = "hidden"
。这应该可以解决问题。
function ToggleSearchBar() {
var searchbar = document.getElementById("SearchBar");
var display = getComputedStyle(searchbar).display;
if (display == "none") {
searchbar.style.opacity = 0;
searchbar.style.display = "block";
var i = 1;
function IncreaseOpacity() {
setTimeout(function() {
searchbar.style.opacity = i * .1;
i++;
if (i <= 10) {
IncreaseOpacity();
}
}, 30)
}
IncreaseOpacity();
} else {
var v = 10;
function DecreaseOpacity() {
setTimeout(function() {
searchbar.style.opacity = v * .1;
v--;
if (v >= 0) {
DecreaseOpacity();
} else {
searchbar.style.visibility = "hidden";
}
}, 30)
}
DecreaseOpacity();
}
}
<div class="search-button">
<p onclick="ToggleSearchBar()">Search</p>
<form id="SearchBar">
<input type="text" placeholder=" Your query here">
</form>
</div>