更改活动页面的颜色(分页)
问题描述:
我在想如何更改活动页面的颜色?这个函数不工作,我真的不想把它作为输入类型=“按钮”...因为它看起来更糟糕。我在这里错过了什么?更改活动页面的颜色(分页)
<form1>
<script>
function btnColor(btn, color) {
var property = document.getElementById(btn)
property.style.backgroundColor = color;
}
</script>
<div class="pagination">
<a id="pageOne" onclick="btnColor('pageOne','#ffcce9');">1</a>
<a id="pageTwo" onclick="btnColor('pageTwo','#ffcce9');">2</a>
<a id="pageThree" onclick="btnColor('pageThree','#ffcce9');">3</a>
</div>
</form1>
答
CSS类,让我们试试这个(On Click事件在HTML中不一个很好的做法)
<form1>
<div class="pagination">
<a id="pageOne">1</a>
<a id="pageTwo">2</a>
<a id="pageThree">3</a>
</div>
</form1>
<script>
links = document.querySelectorAll("a")
links.forEach(function (item) {
item.addEventListener('click', function() {
//reset the color of other links
links.forEach(function (item) {
item.style.backgroundColor = '#fff'
})
// apply the style to the link
this.style.backgroundColor = '#ffcce9'
});
})
</script>
答
<form1>
<script>
window.addEventListener("onload",function(){
console.log("loaded");
["pageOne","pageTwo","pageThree"].forEach(function(id){
console.log(id);
document.getElementById(id).addEventListener("click",function(){
console.log(this);
this.style.backgroundColor=,'#ffcce9';
});
});
});
</script>
<div class="pagination">
<a id="pageOne" >1</a>
<a id="pageTwo" >2</a>
<a id="pageThree" >3</a>
</div>
</form1>
只需使用JS的onclick听所有点击...
答
可以遍历所有的页面选项卡,并确定它们是否有效。如果不是,从不活跃的删除css类和活性一个
例下面添加
.color{
background:#ffcce9
}
.pages:hover{
cursor:pointer
}
<form1>
<script>
function btnColor(btn, color) {
property = document.getElementById(btn);
property.classList.add("color");
var all_pages = document.getElementsByClassName("pages");
for (x = 0; x < all_pages.length; ++x) {
if (all_pages[x].classList.contains("color") && all_pages[x] != property) {
all_pages[x].classList.remove("color");
} //end if
}
}
</script>
<div class="pagination">
<a id="pageOne" class="pages" onclick="btnColor('pageOne','#ffcce9');">1</a>
<a id="pageTwo" class="pages" onclick="btnColor('pageTwo','#ffcce9');">2</a>
<a id="pageThree" class="pages" onclick="btnColor('pageThree','#ffcce9');">3</a>
</div>
</form1>
答
的整点就是改变页面的背景颜色吧?这应该做的伎俩。如前所述,onclick
并不是很好的做法。
<body>
<button data-color="black">Page 1</button>
<button data-color="blue">Page 2</button>
<script>
var buttons = document.querySelectorAll('button');
buttons.forEach(function (button) {
button.addEventListener('click', function() {
var color = button.dataset.color;
document.body.style.background = color;
});
});
</script>
</body>
+0
不,不是,我的意思是页码的背景颜色 - 显示我们目前正在查看哪个页面。有像这样的分页https://www.w3schools.com/howto/howto_css_pagination.asp,我想改变一个活动的背景。 – Mary
工作! :)惊人的,非常感谢! – Mary