2016-05-26 16 views
1

我已經對齊元素中的某些文本。我可以通過JavaScript或jQuery獲得文本偏移像素的位置嗎?在CSS文本對齊樣式後獲取文本的相對位置

的例子如下:

<html> 
 
    <head> 
 
    </head> 
 
    <body> 
 
    <p style="text-align: right; background-color:green; width: 80%;">This text is right aligned.</p> 
 
    </body> 
 
</html>

有沒有辦法知道有空間的像素有文本的開始前?換句話說,在上面的例子中,我需要知道在「This text ...」的第一個字母之前綠色區域有多少像素寬度。

更重要的是,如果我拖動瀏覽器並改變它的寬度,我可以動態地知道像素的空間嗎?

回答

0

如果您給文本打包元素(在<p>內),可以通過比較包裝的offsetWidth<p>來完成。如果文本右對齊,則任何寬度差必須是左側的空格。

要檢查的位置是什麼窗口大小後,聽取了窗口上的resize事件,按以下步驟進行:

// I've placed the important stuff in this function 
 
// so I can use it as an event handler 
 
function updateWidth() { 
 

 
    // Get width of the text (requires a wrapping element, such as <span>) 
 
    var innerWidth = getElement('inner').offsetWidth; 
 

 
    // Get width of surrounding <p> 
 
    var outerWidth = getElement('outer').offsetWidth; 
 

 
    // Subtract to get the amount of space on the left 
 
    var leftSpace = outerWidth - innerWidth; 
 

 
    // Output it (since I have nothing better to do) 
 
    getElement('output').innerHTML = 'left space = ' + leftSpace + 'px'; 
 

 
} 
 

 
// Update the amount of space when the window is resized 
 
window.addEventListener('resize', updateWidth); 
 

 
// Run the function once to display the amount of space 
 
// before the user has resized the window 
 
updateWidth() 
 

 

 
// Just a utility (since I'm not using jQuery) 
 
function getElement(id) { 
 
    return document.getElementById(id); 
 
};
<!-- There is a wrapping span here --> 
 
<p id="outer" style="text-align: right; background-color:green; width: 80%;"><span id="inner">This text is right aligned.</span></p> 
 

 
<!-- This is only for outputting the width --> 
 
<pre id="output"></pre>

如果父<p>填充並且父項設置爲box-sizing: border-box,那麼還要從父項寬度中減去填充量。