2013-01-21 43 views
3

在jQuery中,zepto.js等可以說如何在HTML中獲取元素的形狀/多邊形/邊界路徑/框架?

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

但一個標籤可以跨越幾行的形狀不是一個簡單的矩形(位置和大小)更加複雜。我想得到的是元素的路徑。

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. 

那麼,有沒有什麼辦法讓任何元素的多邊形?

回答

1

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

這會給你一個鏈接的每一行的邊界點。由於構建一個poly將取決於形狀,所以我沒有真正有時間去了解這一點,但我認爲這是一個合理的出發點。

希望它有幫助!

$(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 
+0

太棒了!你認爲CPU很重嗎?你基本上是將每個單詞放在一個範圍內,更新DOM,然後獲得eahch單詞的位置? – hfossli

+0

是的,這是方法。它會在CPU上稍微滑動一點,但對於50-100個單詞,這可能是合理的。我還注意到,最右邊的單詞需要添加到它們的寬度,底部單詞需要高度,我已經更新了小提琴和代碼。 – mattdlockyer