html 重新定位类元素

sr4lhrrt  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(72)

我有一个眼睛图标,当你点击它时,图标会改变,并通过js:left: 10%;重新定位。
但是,如果DOM中有一个ID为login-section的元素,则应将其重新定位为left: 50%;
我试过document.getElementsByClassName('fa-eye-slash').style.left = '50%';,但它不工作。

let eye = document.querySelectorAll('.eye');
eye.forEach(function (v) {
    v.addEventListener('click', function () {
        this.classList.toggle('fa-eye-slash');
    

        if(document.getElementById('login-section')) {
            // Following line is not working:
            document.getElementsByClassName('fa-eye-slash').style.left = '50%';
        }
       

    })
});
.eye {
    position: absolute;
}
.fa-eye-slash {
    left: 10%;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">

<div id='login-section'>
    <i class="fa-solid fa-eye eye"></i>
</div>
t30tvxxf

t30tvxxf1#

你应该选择被点击的类为.fa-eye-slash的元素本身。现在,看起来你正在尝试设置所有类为.fa-eye-slash的元素的left属性。
另外,你可以使用style属性来设置CSS样式。但是,由于你想在两个位置之间切换,最好添加和删除一个定义了left属性的CSS类。
这里有一个例子,可能会有所帮助:

let eye = document.querySelectorAll('.eye');

eye.forEach(function (v) {
    v.addEventListener('click', function () {
        this.classList.toggle('fa-eye-slash');

        if (document.getElementById('login-section')) {
            if (this.classList.contains('fa-eye-slash')) {
                this.style.left = '50%'; 
            } else {
                this.style.left = '10%'; 
            }
        }
    });
});

字符串

相关问题