我有一些 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 );
}
});
最佳答案
已更新
这个元素在显示元素时移动(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 );
}
};
关于javascript - 移动到[取消]隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23667703/