gpt4 book ai didi

javascript - 如何将样式应用于类的单个元素,同时从同一类的前一个元素中删除样式?

转载 作者:可可西里 更新时间:2023-11-01 13:32:10 25 4
gpt4 key购买 nike

更具体地说,我正在尝试拥有一系列 img tiles,当其中一个被选中时,它会收到一个边框。 When a different image tile is selected of the same class, it will receive the border, while the previous selected img will have it's border removed.

一个很好的例子类似于本网站上的第一个例子: http://rvera.github.io/image-picker/

重要提示:我正在尝试避免使用 jQuery 并找到纯 Javascript 解决方案。没有什么反对 jQuery 的,我只是想在这个元素中避免它。

这是我的代码...

CSS:

<style>
.tile {
width:100px;
height:100px;
cursor:pointer;
}
</style>

JavaScript:

<script>
function example ()
{
var i; // Counter
var tilecount = document.querySelectorAll( '.tile' ).length; // Number of elements of the "tile" class
var tilearray = document.getElementsByClassName( 'tile' ); // All tile elements

for ( i = 0; i < tilecount; i++ )
{
if ( tilearray[i].style.border == 'none' )
{
tilearray[i].style.border = '5px solid #2c2d2d';
}

else
{
tilearray[i].style.border = 'none';
}
}
}
</script>

HTML:

<table>
<tr>
<td><img onclick="example()" class="tile" src="http://i.imgur.com/jlQyrWk.jpg" /></td>
<td><img onclick="example()" class="tile" src="http://i.imgur.com/H6qGF5Z.jpg" /></td>
<td><img onclick="example()" class="tile" src="http://i.imgur.com/76hOij3.png" /></td>
</tr>
</table>

不幸的是,我的代码无法正常工作,我想我应该征求 Stack Overflow 专家的意见。再一次,请不要使用 jQuery。

最佳答案

由于始终最多选择 1 个元素,因此无需遍历所有元素。

您可以简单地将最后一个被点击的对象存储在一个公共(public)变量中。

然后,当您单击一个新元素时,您已经拥有对先前选择的元素的引用。

<table>
<tr>
<td><img onclick="example(this)" class="tile" src="http://i.imgur.com/jlQyrWk.jpg" /></td>
<td><img onclick="example(this)" class="tile" src="http://i.imgur.com/H6qGF5Z.jpg" /></td>
<td><img onclick="example(this)" class="tile" src="http://i.imgur.com/76hOij3.png" /></td>
</tr>
</table>

JS:

var lastSelectedItem;
function example(element) {
if(lastSelectedItem)
lastSelectedItem.style.border = "none";
element.style.border = "1px solid black";
lastSelectedItem = element;
}

http://jsfiddle.net/u05e1gLv/

关于javascript - 如何将样式应用于类的单个元素,同时从同一类的前一个元素中删除样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27464223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com