Javascript 如何获得相对定位的父级
假设我有Javascript 如何获得相对定位的父级,javascript,jquery,css,Javascript,Jquery,Css,假设我有 <body> <article style="left: xxx; top: xxx">...</article> <article style="left: xxx; top: xxx">...</article> <article style="left: xxx; top: xxx">...</article> </body> ... ... ... 我的
<body>
<article style="left: xxx; top: xxx">...</article>
<article style="left: xxx; top: xxx">...</article>
<article style="left: xxx; top: xxx">...</article>
</body>
...
...
...
我的目标是找出“扇区”中的元素,例如上/下/左/右。然后添加用于样式设置的类。所以我想我会的
我知道我的文章是相对于主体定位的,但是如何使用JS/jQuery动态地获得它呢。我正在创建一个插件,所以我不想硬编码相对定位的父对象 Alex Thomas关于正确使用javascript以快速加载和优雅降级的方式增强用户体验的观点是绝对正确的 无论如何,这里有一个概念的快速证明JSFIDLE,它实现了您所描述的功能: 资料来源(粗略):
var$articles=$(“article”);
$articles.each(函数(){
变量$which=$(本);
var$parent=$which.parent();
var className=“”;
var pHeight=$parent.outerHeight();
//警报($which.offset().top++(pHeight/2));
如果($which.offset().top<(pHeight/2)){
类名+=“底部”;
}否则{
类名+=“顶部”;
}
var pWidth=$parent.outerWidth();
//警报($which.offset().left++(pWidth/2));
如果($which.offset().left<(pWidth/2)){
类名+=“左”;
}否则{
类名+=“右”;
}
$which.addClass(类名);
});
你能不能给每篇文章一个id或类“Top/Bottom/Left/Right”,然后得到父元素的id,而不是做一些复杂的计算?你想如何判断元素在哪个“扇区”中?@Corn的Peter,现在我用它,我在想也许可以减少一些标记并挑战自己,我尝试一下that@J-P,与元素左上角相比,我的父元素的宽度/高度可以挑战你自己,但请注意,使用javascript(JS)是为了增强用户体验。在这个问题上,如果你使用JS,它不会优雅地降级,因此不应该使用。如果可以,请使用基本的CSS和XHTML#只是说说而已
var $articles = $("article");
$articles.each(function(){
var $which = $(this);
var $parent = $which.parent();
var className = "";
var pHeight =$parent.outerHeight();
//alert($which.offset().top + " <> " + (pHeight/2));
if($which.offset().top < (pHeight/2)){
className += "Bottom";
} else {
className += "Top";
}
var pWidth =$parent.outerWidth();
//alert($which.offset().left + " <> " + (pWidth /2));
if($which.offset().left < (pWidth/2)){
className +="Left";
} else {
className +="Right";
}
$which.addClass(className);
});