【问题标题】:Get the correct placeholder color with JS使用 JS 获取正确的占位符颜色
【发布时间】:2019-02-20 15:13:42
【问题描述】:

我将输入的默认占位符颜色更改为蓝色。为什么我使用 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>

【问题讨论】:

  • 在 Firefox 56、Windows 7 上运行良好。您使用的是什么浏览器?
  • 铬版本 68.0.3440.106
  • 它可以在 Firefox 61.0.1 中运行。不在 Chrome 69.0.3497.92

标签: javascript html css placeholder


【解决方案1】:

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

下面是一个使用 :placeholder-shown 和 ::placeholder 的 codepen

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}`;
}

【讨论】:

  • 感谢有用的 JS 解决方案。但是对于developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style,window.getComputedStyle() 还必须从外部样式表返回正确的样式属性
  • 我相信如果您在外部工作表中使用正确的伪类和伪事件样式,它应该可以工作,我还没有对此进行测试,但我也没有阅读有关外部工作表的任何错误和getComputedStyle() 带有这个特定的 :placeholder-shown 或 ::placeholder 属性。
  • 仅当输入为空时在 Chromium 中工作
  • 这仅适用于占位符当前在输入元素中使用时的占位符。这就是我阅读 css-tricks 文章的方式。当它不活动时,它应该具有输入默认颜色的值,如果你没有分配它应该是黑色。
  • 这只是一个建议,但也许您可以存储正在使用的值以便以后访问它。
猜你喜欢
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 2012-08-03
  • 2013-01-05
相关资源
最近更新 更多