这里是jquery的新手,我已经提出了一个Ajax框出现在链接下面。它对页面左侧的链接正常工作,但当链接在右侧时,该框与页面对齐不正确。我用的是自动柜员机的绝对定位这就是为什么它会这样对齐。
是否有一种方法可以让它在页面的左侧正确地向右对齐链接,然后在页面的右侧向左对齐链接。真知灼见非常感谢!谢谢!
http://jsfiddle.net/5hUbG这里有一个粗略的方法:
http://jsfiddle.net/PdCHZ/12/[edit]:我更新了它,使用工具提示的宽度从CSS:[edit number 2:]如果你添加这个:
$('<div/>',{html:"", id:'tooltip'}).css({visibility:"hidden"}).prependTo( 'body' );
在$(document).ready(function () {
开头,那么width代码将自动从CSS中获取宽度。
$(document).ready(function () {
$("a.link").click(function () {
var $link = $(this);
$.ajax({
type: "POST",
url: '/echo/html/',
data: {
html:'these would be the returned data form the <strong>AJAX</strong> call..'
},
success: function (response) {
var pos = $link.position();
// this just gts the number of pixels from the left of the screen
// that the element is.
var offset = $link.offset();
//set oWidth to 300 unless you want to create a hidden tooltip
//before this, so that it can read the width from that.
var oWidth = $("#tooltip").width();
// modifier gets set to -oWidth if the link is less than
// pixels from the right of the screen (this makes it pop up
// to the left of the link instead of to the right)
// (if the element is more than 300 from the right, then it gets set to 10, like you had it originally)
var modifier = (offset.left>$(document).width()-oWidth)?-oWidth:10;
$('#tooltip').remove();
// all i've done here is changed your "10" to "oWidth"
// so that it either turns into -300 or +10 depending on
// where the link clicked on is on the screen.
$('<div/>',{html:response, id:'tooltip'}).css({left:pos.left+modifier+'px', top:pos.top+10+'px'}).prependTo( 'body' );
}
});
});
});
您可以将"300"替换为$("#tooltip").width()
之类的东西,这样您就不必更新它,但您可能已经明白了。
奇迹发生在这里:
var modifier = (offset.left>$(document).width()-oWidth)?-oWidth:10;
如果你不熟悉,这只是一个简短的If语句,相当于以下语句:
if(offset.left>$(document).width()-oWidth){
var modifier = -oWidth;
} else {
var modifier = 10;
}
然后你只需要给position .left添加修饰符,你就有了你的定位了
我的建议是:
if ($link.parent().hasClass('right'))
$('#tooltip').css({left:+pos.left + $link.outerWidth() - $('#tooltip').outerWidth() + 'px'});
刚刚添加到您的成功功能的结尾?