html 重新定位类元素

sr4lhrrt  于 2024-01-04  发布在  其他
关注(0)|答案(1)|浏览(103)

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

  1. let eye = document.querySelectorAll('.eye');
  2. eye.forEach(function (v) {
  3. v.addEventListener('click', function () {
  4. this.classList.toggle('fa-eye-slash');
  5. if(document.getElementById('login-section')) {
  6. // Following line is not working:
  7. document.getElementsByClassName('fa-eye-slash').style.left = '50%';
  8. }
  9. })
  10. });
  1. .eye {
  2. position: absolute;
  3. }
  4. .fa-eye-slash {
  5. left: 10%;
  6. }
  1. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
  2. <div id='login-section'>
  3. <i class="fa-solid fa-eye eye"></i>
  4. </div>
t30tvxxf

t30tvxxf1#

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

  1. let eye = document.querySelectorAll('.eye');
  2. eye.forEach(function (v) {
  3. v.addEventListener('click', function () {
  4. this.classList.toggle('fa-eye-slash');
  5. if (document.getElementById('login-section')) {
  6. if (this.classList.contains('fa-eye-slash')) {
  7. this.style.left = '50%';
  8. } else {
  9. this.style.left = '10%';
  10. }
  11. }
  12. });
  13. });

字符串

展开查看全部

相关问题