Посчитать длину элемента
Здравствуйте, скажите, как можно посчитать длину в пикселях длину строки.
Например я ввожу слово: hello world и он мне показывает сколько длина этой фразы. Спасибо. |
Начинающий-Js-кодер,
всё зависит от элемента и его css в котором будет этот текст. |
Ну элемент пусть будет div и он должен создавать динамически с шириной взятой от ширины слова+5px слева и справа.
|
Начинающий-Js-кодер,
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
div {
border: 2px solid green;
}
</style>
</head>
<body>
<script>
function fn(str)
{
var container = document.createElement("div")
container.appendChild(document.createTextNode(str));
document.body.appendChild(container);
container.style.display = "inline"
var width = container.offsetWidth;
container.style.display = "";
container.style.width = width + "px";
container.style.padding = "0 5px";
}
fn("hello world")
</script>
</body>
</html>
|
Спасибо. Гениально. Но вопрос:
container.style.display = "inline" ... container.style.display = ""; Зачем именно так делать? |
Начинающий-Js-кодер,
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
div.test {
border: 2px solid green;
display: inline-block;
padding: 0 5px;
text-align: center;
}
</style>
</head>
<body>
<script>
function fn(str)
{
var container = document.createElement("div")
container.appendChild(document.createTextNode(str));
document.body.appendChild(container);
container.classList.add("test")
}
fn("hello world")
</script>
</body>
</html>
|
Гений!
|
Цитата:
container.style.display = "inline" сужаем ширину до текста (надобы word-wrap: break-word; ещё) container.style.display = ""; возращаем display=block |
Теперь понял. Идеальное решение.
|
Хотел спросить:
Вот допустим есть у нас не 1 слово, а 5(или любое другое) и мы их должны вывести каждый в своем блоке отдельно, то есть так: hello->world->hi->javascript->forum Но расстояние между блоками должно быть строго 30 пикселей, тогда лучше делать не через inline-block, о пределять ширину каждого блока,потом прибавлять 30 пикселей и это будет позиция второго блока, так? |
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
div.test {
border: 2px solid green;
display: inline;
padding: 0 5px;
text-align: center;
margin-right:30px;
}
</style>
</head>
<body>
<script>
function fn(str)
{
var container = document.createElement("div")
container.appendChild(document.createTextNode(str));
document.body.appendChild(container);
container.classList.add("test")
}
var arr = 'hello world hi javascript forum'.split(' ');
arr.forEach(function(it) {
fn(it);
});
</script>
</body>
</html>
|
Спасибо, но а если без margin-right:30px; это сильно будет сложнее?
|
Цитата:
|
Просто если нужно рядом с элементом линию будет нарисовать, а из-за margin-right:30px; она будет на 30 px подальше.
|
Начинающий-Js-кодер,
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
body {
position: relative;
}
div.test {
border: 2px solid green;
display: inline;
padding: 0 5px;
text-align: center;
position: absolute;
}
</style>
</head>
<body>
<script>
function fn(str, left)
{
var container = document.createElement("div")
container.appendChild(document.createTextNode(str));
document.body.appendChild(container);
container.classList.add("test");
container.style.left = left + "px"
return container.offsetWidth
}
var arr = 'hello world hi javascript forum'.split(' '), left = 0;
arr.forEach(function(it) {
left += fn(it,left) + 30;
});
</script>
</body>
</html>
|
проще getComputedStyle
https://learn.javascript.ru/styles-and-classes |
Спасибо огромное
|
| Часовой пояс GMT +3, время: 07:18. |