使用 JS 获取正确的占位符颜色



我将输入的默认占位符颜色更改为蓝色。为什么我在 Javascript 中会得到黑色占位符颜色?

const getPlaceholderColor = () => {
let inputEl = document.querySelector('.myClass');
let inputElStyle = window.getComputedStyle(inputEl, '::placeholder');

let resultTarget = document.getElementById('colorResult');
let placeholderColor = inputElStyle.getPropertyValue('color');
resultTarget.innerHTML = `Placeholder color: ${placeholderColor}`;
}
.myClass::placeholder {
color: #004085;
}
.marginTop20 {
margin-top: 20px;
}
<input
type="text"
placeholder="Enter name"
class="myClass"
/>
<button onClick="getPlaceholderColor()">Get placeholder color</button>
<div class="marginTop20" id="colorResult"></div>

这里写了这个问题=> https://css-tricks.com/almanac/selectors/p/placeholder/

下面是使用:p蕾丝持有人所示和 ::p蕾丝持有人的代码笔

https://codepen.io/kipomaha/pen/pOOdQr

document.getElementById("myStyles").sheet.insertRule('.myClass:placeholder-shown { color: red; }');
document.getElementById("myStyles").sheet.insertRule('.myClass::placeholder { color: red; }');
const getPlaceholderColor = () => {
let inputEl = document.querySelector('.myClass');
let inputElStyle = window.getComputedStyle(inputEl, ':placeholder-shown');
let resultTarget = document.getElementById('colorResult');
let placeholderColor = inputElStyle.getPropertyValue('color');
resultTarget.innerHTML = `Placeholder color: ${placeholderColor}`;
}

document.getElementById("myStyles").sheet.insertRule('.myClass:placeholder-shown { color: red; }');
document.getElementById("myStyles").sheet.insertRule('.myClass::placeholder { color: red; }');
var inputEl = document.querySelector('.myClass'); 
var placeholderColor = inputElStyle.getPropertyValue('color');
const getPlaceholderColor = () => {
let inputElStyle = window.getComputedStyle(inputEl, ':placeholder-shown');
let resultTarget = document.getElementById('colorResult');
resultTarget.innerHTML = `Placeholder color: ${placeholderColor}`;
}

最新更新