gpt4 book ai didi

javascript - 如何在 HTML 中获取元素的形状/多边形/边界路径/框架?

转载 作者:可可西里 更新时间:2023-11-01 14:53:26 26 4
gpt4 key购买 nike

在 jQuery、zepto.js 等中你可以说

var position = $('a:first').position();

但是 a-tag 可以跨越多行,其形状比简单的矩形(位置和大小)更复杂。我想得到的是元素的路径。

例子

The pipes in this examples is meant to illude ||||||| 
|||||| |||| || ||||||| an a-tag spanning over two lines.
Consisting of two different rects OR 8 different points.

那么,有什么办法可以得到任意元素的多边形吗?

最佳答案

http://jsfiddle.net/mattdlockyer/EEVV2/

这将为您提供链接每行的边界点。

由于构建多边形将取决于形状,我真的没有时间深入了解这个,但我认为这是一个合理的起点。

希望对您有所帮助!

$(document).ready(function () {
var words = $('a').text().split(' '); //break the link's words into array
for (var i = 0; i < words.length; ++i) {
words[i] = '<span>' + words[i] + '</span> '; //wrap each word in a span
}
words.join(' '); //join the words
$('a').html(words); //replace the link html with the words wrapped in spans

var points = []; //to store our points
var lastIndex = $('a span').length - 1; //so we know we've hit the last point
var first; //keep track of first point

$('a span').each(function (i) {
var pos = $(this).position();
if (i > 0) {
if (i != lastIndex) {
if (points[points.length - 1].top < pos.top) { //have we hit a new line?
var newPos = $($('a span')[i - 1]).position();
if (newPos.left != first.left) { //check if we are on the right side of the object
newPos.left += $($('a span')[i - 1]).width(); //add the width of the word
points.push(newPos); //push this point
} else {
points.push(newPos); //we are on the left side, push the point without the width of the word
}
//$($('a span')[i - 1]).addClass('red'); //useful for debugging
}
} else {
var bottomLineHeight = $(this).height();
pos.left += $(this).width(); //add width to last point
pos.top += bottomLineHeight; //add height to last point, push later
points[points.length - 1].top += bottomLineHeight; //add height to second to last point
points.push(pos); //push last point
}
} else {
points.push(pos); //push first point
first = pos; //keep track of topLeft point (first)
}
});

//for printing out points
var html = '';
$(points).each(function (i, obj) {
html += '<p>(' + obj.left + ', ' + obj.top + ')';
});
$('#result').html(html);

});//ready

关于javascript - 如何在 HTML 中获取元素的形状/多边形/边界路径/框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14440322/

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