gpt4 book ai didi

javascript - getClientRects 不适用于 safari 或 chrome 中的图像

转载 作者:行者123 更新时间:2023-12-03 09:45:45 25 4
gpt4 key购买 nike

我正在尝试获取不同元素的边界矩形。我使用 getClientRects 获取元素的矩形,然后在该矩形上绘制一个红色 div。在 Firefox 上它可以工作,但在 chrome 和 safari 中我得到奇怪的结果。在 safari 上的 jsfiddle 上它可以工作,但 safari 中的相同代码直接不能工作,因此很难显示问题。

http://jsfiddle.net/pmnwjc33/5/

在 safari 中,如果我尝试查找图像和输入的边界框,我会得到图像的上、左、下、右矩形为 8,8,8,8。因此图像的边界框不正确,并且似乎会丢失图像后面的任何边界框。有什么方法可以使其正常工作吗?

红框是矩形 enter image description here

    <html>
<body>
<input id="cart1" type=button value="AddToCart" ><br>

<img id="dogimage" src="http://www.petyourdog.com/uploads/articles/17-6.jpg">
<input id="cart2" type=button value="AddToCart2" ><br>

</body>

</html>

<script>
function addClientRectsOverlay(elt) {
console.log(elt.tagName);
// Absolutely position a div over each client rect so that its border width
// is the same as the rectangle's width.
// Note: the overlays will be out of place if the user resizes or zooms.
var rects = elt.getClientRects();
console.log(rects.length);

for (var i = 0; i != rects.length; i++) {

var rect = rects[i];
console.log(rect);
if(elt.tagName=="IMG"){
console.log(rect.top);
console.log(rect.bottom);
console.log(rect.right);
console.log(rect.left);
console.log(parseInt(rect.right)-parseInt(rect.left));
console.log(parseInt(rect.bottom)-parseInt(rect.top));
}

var tableRectDiv = document.createElement('div');
tableRectDiv.style.position = 'absolute';
tableRectDiv.style.border = '1px solid red';
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
tableRectDiv.style.margin = tableRectDiv.style.padding = '0';
tableRectDiv.style.top = (rect.top) + 'px';
tableRectDiv.style.left = (rect.left) + 'px';
// we want rect.width to be the border width, so content width is 2px less.
tableRectDiv.style.width = (rect.width - 2) + 'px';
tableRectDiv.style.height = (rect.height - 2) + 'px';
document.body.appendChild(tableRectDiv);
}
}

var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
if(all[i].tagName!="BR"){
addClientRectsOverlay(all[i]);
}
}

</script>

最佳答案

Firefox 从版本 3 开始、Opera 从版本 9.5 开始以及 Safari 从版本 4 开始支持 getClientRects 方法。

因此,它在 Chrome 中不起作用。

关于javascript - getClientRects 不适用于 safari 或 chrome 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com