[英]jQuery animation not working in anchor tags or anchor tag children
我花了一天的大部分時間來追蹤我在使用jQuery動畫時遇到的問題。 至少在運動動畫方面,將jQuery.animate()應用於錨元素或錨元素內部的子元素似乎存在問題。 我將問題簡化為一個說明問題的簡單示例:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
var foo = {};
function TestMove(newx, newy) {
this.newx = newx;
this.newy = newy;
}
TestMove.prototype = {
movex:function () {
$("#newsec").animate({left: this.newx + "px"});
},
movey:function () {
$("#newsec").animate({top: this.newy + "px"});
}
}
function bar() {
foo[1].movex();
foo[1].movey();
}
function init() {
foo[1] = new TestMove(200,200);
}
</script>
</head>
<body onload="init()">
<a href="" style="position: relative;">
<div style="position: relative; height: 50px; width: 50px; background-color: red;" id="newsec" onclick="bar()"></div>
</a>
</body>
</html>
無論我將id屬性和onclick事件處理程序調用放在<a>標記中還是在其中的<div>中,動畫均不起作用。 另一方面,如果我完全刪除了<a>元素標簽,則動畫將在<div>元素上按預期工作。
有誰知道為什么會這樣嗎?
這個問題幾乎沒有意義,因為我可以輕松地在工作頁中使用<div>元素,而我也可以輕松地使用<a>元素。 在工作代碼中(更復雜),我在錨元素上使用event.preventDefault(),以便鏈接和其他操作由顯式事件處理程序驅動,這也可以從<div>進行。 我相信,當人們在<div>上進行鼠標懸停時,我什至可以更改指針圖標,以便它在這方面也可以模仿真正的錨點。
這是因為瀏覽器將在放置動畫之前定位到錨點。 有一些插件可以解決這類問題,也可以將它們組合在一起。
http://briangonzalez.org/arbitrary-anchor
一個簡單的實現示例:
jQuery.fn.anchorAnimate = function(settings) {
settings = jQuery.extend({
speed : 1100
}, settings);
return this.each(function(){
var caller = this
$(caller).click(function (event) {
event.preventDefault()
var locationHref = window.location.href
var elementClick = $(caller).attr("href")
var destination = $(elementClick).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
window.location.hash = elementClick
});
return false;
})
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.