onclick="&引用;javascript内联问题

onclick="&引用;javascript内联问题,javascript,html,onclick,Javascript,Html,Onclick,我发现了一个很好的用于平滑滚动功能的纯javascript代码,但我不知道如何使用onclick内联函数使其工作。 我相信这很简单,但是我在javascript方面很弱 <div class="navbar"> <button type="button" id="clickme">scroll whit class</button> <button type="button" onclick="smoothScroll(third)" >n

我发现了一个很好的用于平滑滚动功能的纯javascript代码,但我不知道如何使用onclick内联函数使其工作。 我相信这很简单,但是我在javascript方面很弱

<div class="navbar">
  <button type="button" id="clickme">scroll whit class</button>
  <button type="button" onclick="smoothScroll(third)" >not working yet</button>
 </div>

<div class="third" id="third">The start of the red section!</div>
正如您所看到的,有一个id为的准备就绪的getElement,但我想删除它,使它只在内联模式下工作

onclick="smoothScroll(second)"
onclick="smoothScroll(third)"
onclick="smoothScroll(fourth)"
等等。。。。
这是一个

尝试使用此选项将有助于平滑滚动,而且使用起来太简单了

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
所有你需要的是有一个链接

<a href="#third">not working yet</a>
<div id="third"></div>

这将在绑定到任何div(href(用于链接)和id(用于div))的任何链接上顺利运行。请注意这两个属性,这样做会很好

您也可以在下面的链接中找到演示examle将向您解释更多内容


您的小提琴与问题中提供的代码不同。假设您的Fiddle是最新的版本,它就不起作用了,因为您有两个具有相同id的按钮,根据HTML规范,这是无效的

<button type="button" id="clickme">scroll whit class</button>
<button type="button" id="clickme">scroll whit onclick=""</button>
您可以通过向第二个按钮添加不同的id来解决此问题:

<button type="button" id="clickme">scroll whit class</button>
<button type="button" id="clickme1">scroll whit onclick=""</button>
或者更简洁一些,您可以向按钮添加一个类,并迭代
document.getElementsByClassName的结果

var scrollContainer = document.getElementById(target);
target = document.getElementById(target);
然后在你的html中

<button type="button" onclick="smoothScroll('third')" id="clickme">scroll whit onclick=""</button>
滚动whit onclick=“”
工作小提琴手

document.getElementById
添加到
smoothScroll
并使用
onclick=“smoothScroll('second')”
是否要使用
onclick
属性?别再想要了。这不是1997年。它们有令人兴奋的gotchas,使用它们并不被认为是最佳实践。这不是我是否愿意,在我的情况下,我必须使用onclick。谢谢你的意见,但你一点帮助都没有。工作小提琴手你的小提琴代码与你问题中的代码不同。要使用的正确代码是什么?如果需要,请更新您的问题。这与要求的问题无关。张贴的小提琴与问题不同。因为小提琴包含了一些评论的反馈。这似乎是最近的事,我会要求海报澄清标题内联提到的主题。Javascript addEventListener不是内联的
function scrollDiv() 
{
    var header = document.querySelectorAll('.navbar');
    aim = -header[0].clientHeight;
    initial = Date.now();

    smoothScroll(document.getElementById('third'));
}

document.getElementById('clickme').addEventListener('click', scrollDiv)
document.getElementById('clickme1').addEventListener('click', scrollDiv)
var scrollContainer = document.getElementById(target);
target = document.getElementById(target);
<button type="button" onclick="smoothScroll('third')" id="clickme">scroll whit onclick=""</button>