香草Javascript。滚动时更改元素的样式。

时间:2017-01-10 10:00:29

标签: javascript scroll offset

如果我有一个简单的标题,在固定位置设置样式,如下所示。如何(在vanilla JavaScript中)我可以在滚动时更改颜色,例如向下滚动200px(标题的高度)。我可以在stackoverflow上找到的所有示例仅适用于JQuery。

body {
  height: 2000px;
}

 header {
   width: 100%;
   height: 200px;
   background-color: red;
   position: fixed;
 }
<body>

    <header>
      <h1>This is the header I want to change</h1>
    </header>

 </body>

2 个答案:

答案 0 :(得分:0)

function runOnScroll() {
    if (document.body.scrollTop >= 200) {
     var h1 = document.getElementsByTagName("h1")[0];
      h1.style.color = "green";
      }
 }; 
window.addEventListener("scroll", runOnScroll);
body {
  height: 2000px;
}

 header {
   width: 100%;
   height: 200px;
   background-color: red;
   position: fixed;
 }
<body>

    <header>
      <h1>This is the header I want to change</h1>
    </header>

 </body>

答案 1 :(得分:0)

这可能会引导您朝着正确的方向前进:

// external.js
var doc, bod, htm;
addEventListener('load', function(){
  doc = document; bod = doc.body; htm = doc.documentElement;
  addEventListener('scroll', function(){
    doc.querySelector('header').style.backgroundColor = htm.scrollTop > 199 ? 'blue' : 'red';
  });
});
/* external.css */
body{
  height: 2000px;
}
header{
  width: 100%;
  height: 200px;
  background-color: red;
  position: fixed;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <header>
    <h1>This is the header I want to change</h1>
  </header>
</body>
</html>