我有一些jQuery我试图以一种特定的方式工作。我想隐藏和取消隐藏一个元素,并在曝光后将焦点放在曝光区域。有一个链接#welcomeselect,点击时应该公开隐藏的元素#welcome。如果我单击带有以下代码的链接,它将仅取消隐藏元素;如果我再次点击它,那么它将然后移动到显示的元素。我在另一个网站上找到的自定义显示代码(scrollToAnchor);我只需要能够移动到取消隐藏元素,平滑过渡不是必需的。我究竟做错了什么。
$('#welcomeselect').click(function(){
$('#welcome').show();
scrollToAnchor("#welcome");
});
// scroll handler http://bradsknutson.com/blog/smooth-scrolling-to-anchor-with-jquery/
var scrollToAnchor = function( id ) {
// grab the element to scroll to based on the name
var elem = $("a[name='"+ id +"']");
// if that didn't work, look for an element with our ID
if ( typeof( elem.offset() ) === "undefined" ) {
elem = $("#"+id);
}
// if the destination element exists
if ( typeof( elem.offset() ) !== "undefined" ) {
// do the scroll
$('html, body').animate({
scrollTop: elem.offset().top
}, 1000 );
}
};
// bind to click event - http://bradsknutson.com/blog/smooth-scrolling-to-anchor-with-jquery/
$("a").click(function( event ) {
// only do this if it's an anchor link
if ( $(this).attr("href").match("#") ) {
// cancel default event propagation
event.preventDefault();
// scroll to the location
var href = $(this).attr('href').replace('#', '')
scrollToAnchor( href );
}
});
答案 0 :(得分:1)
<强>更新强>
这个元素在显示元素时移动(你在id中只有一个额外的哈希):
$('#welcomeselect').click(function(){
$('#welcome').show();
scrollToAnchor("welcome");
});
的上一页强>
在这里,只有在元素显示后才会移动:
$('#welcomeselect').click(function(){
$('#welcome').show(function(){
scrollToAnchor("welcome");
});
});
var scrollToAnchor = function( id ) {
// grab the element to scroll to based on the name
var elem = $("a[name='"+ id +"']");
// if that didn't work, look for an element with our ID
if ( typeof( elem.offset() ) === "undefined" ) {
elem = $("#"+id);
}
// if the destination element exists
if ( typeof( elem.offset() ) !== "undefined" ) {
// do the scroll
$('html, body').animate({
scrollTop: elem.offset().top
}, 1000 );
}
};