简体   繁体   中英

How I can count the space between left border and begin of a text in the text-align: centered div?

<div style='text-align: center; width: 300px'>test me</div>

所以我需要左边的一个边距左边的px到div中字符串的第一个字母?

The only way to count the distance between a character, and its container is by adding an inline element before the text, then substract the left offset of the parent from the placeholder (using .offset() ).

Example ( DEMO: http://jsfiddle.net/LM8xL/ )

HTML:

<div id="some-div" style='text-align: center; width: 300px'>test me</div>

JavaScript:

var $elem = $("#some-div"),     // Select element
    $placeholder = $("<span>"); // Create inline placeholder
$elem.prepend($placeholder);    // Add placeholder before its contents

// Calculate distance
var distance = $placeholder.offset().left - $elem.offset().left;
$placeholder.remove();          // Remove placeholder
alert(distance);                // Example: Display result

也许用另一个元素( span )包装你的文本并将它与你的div进行比较.offsetLeft

As Kalashnikov said you need to wrap your text in a span tag but some extra work needs to be done. You need to get the span position and the parent (div) offset and subtract them to get the answer. Here is the code:

var position = $("span").position();
var parentOffset = $("span").parent().offset();
var left = position.left - parentOffset.left;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM