首页 > 解决方案 > if else语句javascript使div根据.scrollTop改变颜色

问题描述

我是一名初学者编码器,我正在尝试根据网页向下滚动的距离来更改 div 的背景颜色,我哪里出错了?我需要放入一些东西来调用scrollTop金额吗?

(function () { 
    var scroll = .scrollTop;

if (scroll > 50) {
      document.getElementByClassName("shop").style.backgroundColor = '#99C262';
    }
    else
    {
document.getElementByClassName("shop").style.backgroundColor = ‘red’;

    }
  })(); 

标签: javascript

解决方案


丢掉点,而不是“.shop”去“shop”</p>

而实际的函数 getElement s ByClassName 它返回一个带有类名的 div 集合。但是您需要第一个(假设您只有一个这样的 div),因此数组中的索引为 0

parentDOM.getElementsByClassName('test')[0].style.backgroundColor = "red"; 
 <p class="test">hello here</p>

推荐阅读