Javascript - 获取框架元素到根父框架的协调
我想获得X按钮与图片中的根文档的协调。Javascript - 获取框架元素到根父框架的协调
我尝试使用jQuery的offsetLeft,但是它只返回当前帧的x:
$(window).on('click',
function(e){
console.log("x: " + e.target.offsetLeft);
}
);
http://i.imgur.com/Fdfr31x.jpg
所以我想知道,有没有方法在这种情况下直接获得x?
尝试
$("button").on('click', function()
{
// Your code
});
在这种情况下,x的值将是8作为主体的默认余量是8像素。
$("button").on('click',
function(e) {
console.log("x: " + e.target.offsetLeft);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button</button>
你的方法只返回当前帧的x。 –
你可以让ith清楚吗? –
标签本身是一个单独的文档。所以当你得到offsetLeft时,它只能取当前文档/框架的x(在我的图片中是第3列)。 –
一个javascript添加到每个文件:
$(window).on('click',
function(e) {
console.log(getLeft()+e.target.offsetLeft);
}
);
function getLeft() {
if (window.parent!=window) {
var result="foo";
$(window.parent.document).find("iframe").each(function() {
if ($(this)[0].contentWindow==$(window)[0]) {
result=this.offsetLeft+window.parent.getLeft();
}
});
if (result!="foo") return result;
}
return 0;
}
含test2.html
一个HTML的样本是:
<html>
<head>
<style>
iframe {
position: absolute;
left: 50%;
top: 0px;
width: 50%;
height: 100%;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<button>foo</button>
<iframe src="test2.html"></iframe>
</body>
</html>
这是通过获取位置来自父级的iframe。
如果您有任何疑问,请随时对此发表评论:)
P.S. <frame>
已过时/弃用。示例使用。
但在我的情况下,它有2个父母。我怎样才能得到根父母? –
嗨,理查德,谢谢你的回答。但似乎我们需要将包含'getLeft'方法的js文件插入到“每个”html文件中? 在我的情况下,该项目只包含1个与浏览器交互的js文件(因为我们不控制html文件,它可以是任何网页)。因此,当我再次遇到代码'window.parent.getLeft()'时,它不能在父级中调用'getLeft'方法(因为父级中没有该方法) 我想再次打扰你。 –
是的,您需要将js插入每个文件。如果你只能控制一个单独的html,你可以尝试通过一个文件的javascript动态地将脚本插入到它的父母/孩子。 –
也许使用'$(document)'而不是'$(window)'? – Huelfe