3

我有一个<button>为了在单击时将页面滚动到特定的 DIV ( #contact)

<button onclick="location.href='#contact';">Click Me</button>

如何在 Javascript 中定义它?

$('button[onclick^="#"]').on('click',function (e) {
// Some stuffs here...
});

我正在使用它来动画从 abutton到 DIV 的滚动:

$('a[href^="#"]').on('click',function (e) {
.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});

但它只适用于a hrefs 因为它的a[href^="#"]. 所以我有兴趣让它在我<button>的 s上工作

4

5 回答 5

2

定义按钮

<button class="jumper" data-href="#contact">Click Me</button>

附加点击事件。

$('button.jumper').click(function (e) {
    // new location
    location.href= $(this).data().href;
});
于 2013-09-11T12:15:12.510 回答
0

你也可以用锚标签来做<a>

Top <a href="#bottom">Go to Bottom</a>

<div id="bottom">
Bottom
</div>

参考上面的示例代码

于 2013-09-11T12:16:36.053 回答
0

html

<button id="clicker" onclick="location.href='#contact';">Click Me</button>

jQuery

$('#clicker').click(function (e) {
  $.scrollTo($('#somediv'), 300);
});
于 2013-09-11T12:20:02.697 回答
0

jQuery

给你的按钮

$('button[onclick^="location.href=\'#"]').on('click',function (e) {
 e.preventDefault();
 var target = this.hash,
 $target = $(target);
 $('html, body').stop().animate({
  'scrollTop': $target.offset().top
 }, 900, 'swing', function () {
  window.location.hash = target;
 });
});

一种jQuery 方法来获取包含值为 'location.href=#' 的单击事件的按钮

$('button[onclick^="location.href=\'#"]').on('click',function (e) {
 // Some stuffs here...
}

在 javascript 中查找/创建按钮和定义 onclick 事件的方法:

搜索第一个按钮(注[0])

document.getElementsByTagName('button')[0].onclick=function(){
 location.href='#contact';
}

通过 id 获取按钮(注意 'myButton')

document.getElementById('myButton').onclick=function(){
 location.href='#contact';
}

动态创建整个按钮并将其添加到正文

var button=document.createElement('button');
button.onclick=function(){
 location.href='#contact';
}
document.body.appendChild(button);

找到按钮的现代方法

var button=document.querySelector('button');

var button=document.querySelectorAll('button')[0];

B纯javascript方法来获取包含值为'location.href =#'的点击事件的按钮

var buttons=document.querySelectorAll('button[onclick^="location.href=\'#"]');

非即事件

button.addEventListener('click',function(){
 location.href='#contact';
},false);

即事件

button.attachEvent('onclick',function(){
 location.href='#contact';
});

任何问题?

于 2013-09-11T12:31:16.083 回答
0

尝试这个:

HTML:

<input type="submit" value="submit" name="submit" onclick="myfunction()">

jQuery:

<script type="text/javascript">
 function myfunction() 
 {
    // do whatever you want
 }
</script>
于 2017-08-26T17:11:42.113 回答