gpt4 book ai didi

javascript - 错误地计算元素的宽度

转载 作者:行者123 更新时间:2023-11-29 15:08:24 24 4
gpt4 key购买 nike

我正在尝试计算 block 的宽度,id="titleText" 虽然计算不正确,但我运气不错。

例如,当为空时它仍然显示像素(默认情况下,它应该是一个),但在这个例子中仍然是 18px:

(使用onkeydown)

enter image description here

(使用onkeyup)

enter image description here

和...

在我指定的数字之前触发我的样式逻辑,即 585enter image description here

我的 HTML 是:

<input type="text" autocomplete="off" id="serpTitle" 
onkeydown="checkTitleValue()" class="form-control" />

<p class="d-block" id="titleText"></p>

和 Javascript

function checkTitleValue() {
var fontSize = 12;
var measureTitle = document.getElementById("titleText");
measureTitle.style.fontSize = fontSize;
var height = (measureTitle.clientHeight + 1) + "px";
var width = (measureTitle.clientWidth + 1) + "px"
var inputTitle = document.getElementById("serpTitle").value;

document.getElementById("titleText").innerText = inputTitle;
document.getElementById("titlePixels").innerText = width;

if (measureTitle.clientWidth + 1 > 585) {
document.getElementById("titlePixels").style.color = "red";
}
else if (measureTitle.clientWidth + 1 < 585)
{
document.getElementById("titlePixels").style.color = null;
}
}

最佳答案

你能试试这个代码片段吗?我不明白这个 measureTitle.clientWidth + 1 的意义或 measureTitle.clientWidth + 1 < 585 enter image description here enter image description here

const FONT_SIZE = 12;
const MAX_LENGTH = 585;
var serpTitle = document.getElementById('serpTitle');
var mesured = document.getElementById('measured');
var maxLength = document.getElementById('max-length');
var measureCont = document.getElementById('mesure-cont');
function init() {
measureCont.style.fontSize = FONT_SIZE;
maxLength.innerHTML = MAX_LENGTH + 'px';
updateMesure();

}
function updateMesure() {
measureCont.innerHTML = serpTitle.value;
mesured.innerHTML = measureCont.clientWidth;
}
function checkTitleValue() {
updateMesure();
if (measureCont.clientWidth > MAX_LENGTH) {
measured.style.color = 'red';
} else {
measured.style.color = null;
}
}
init();
<div>
<input type="text" autocomplete="off" id="serpTitle" onkeyup="checkTitleValue()"
class="form-control" />
<span id="measured"></span>/<span id="max-length"></span>
</div>
<div>
<span style="display: inline-block" id="mesure-cont">aaaaa</span>
</div>

关于javascript - 错误地计算元素的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57493475/

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