最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property 'offsetTop' of null - Stack Overflow

programmeradmin1浏览0评论

Hi I have problem with my code. I am trying to do simple scroll function, but i still received an error.

    <script>
    function pageScroll(el) {
    var yPos;
    page = document.getElementById(el);
    var height = page.offsetTop;

    window.scroll(0, height);
    }
</script>

<button class="module-box" onclick="pageScroll(about)">READ</button>

Hi I have problem with my code. I am trying to do simple scroll function, but i still received an error.

    <script>
    function pageScroll(el) {
    var yPos;
    page = document.getElementById(el);
    var height = page.offsetTop;

    window.scroll(0, height);
    }
</script>

<button class="module-box" onclick="pageScroll(about)">READ</button>
Share Improve this question asked May 26, 2016 at 9:46 matimati 971 gold badge3 silver badges11 bronze badges 5
  • This means page doesn't store what you think it does. – Mitya Commented May 26, 2016 at 9:47
  • 1 Try sending the argument as a string - instead of pageScroll(about) try using pageScroll('about'). This should do the trick. – Leo Napoleon Commented May 26, 2016 at 9:49
  • I suppose that the problem lies in the variable page, but you can explain to me what I'm doing wrong? – mati Commented May 26, 2016 at 9:50
  • @LeoNapoleon THANKS! – mati Commented May 26, 2016 at 9:51
  • about should be a string to be able call getElementById so replace pageScroll(about) with pageScroll('about') – Vladu Ionut Commented May 26, 2016 at 9:51
Add a ment  | 

1 Answer 1

Reset to default 2

Working code. Need to pass id as string to the function.

function showTop(el)
{
  var page = document.getElementById(el);
    var height = page.offsetTop;
  alert(height);
  }
<div id="new"></div>
<button onclick = "showTop('new')">Click me</button>
  <div id='op'></div>

发布评论

评论列表(0)

  1. 暂无评论