window.getComputedStyle获取<input type='text'>样式与视觉表现不符问题
问题:复制浏览器文本框样式时
getComputedStyle结果与视觉表现不一致 我希望复制浏览器用户代理样式表中的文本框样式,来创建自己的HTML复合控件。于是使用window.getComputedStyle获取一个简单的<input type='text'>元素的用户代理样式,但发现通过该方法得到的CSS样式与浏览器实际渲染的<input type='text'>元素视觉表现不一致,具体问题如下:
- 显示的文本框带有圆角边框,但获取到的样式中没有相关设置;
- 未聚焦状态下的文本框边框很细,但获取到的样式却是难看的厚重类3D边框。
我在多款浏览器中进行了测试,均存在该问题,只是具体表现略有不同,结论是计算样式与视觉表现不匹配。
测试代码
TS+JQuery
$(document).ready(function () { function build(name: string, pseudoCls: string = undefined): string { var x = window.getComputedStyle($("#t1")[0], pseudoCls); var z = window.getComputedStyle($("#d1")[0], pseudoCls); var newStyle = "." + name; if (pseudoCls) { newStyle += ":" + pseudoCls; } newStyle += "{\n"; let alreadyExistingProps : { [key: string]: string } = {}; for (let i = 0; i < z.length; i++) { let prop = z.item(i); let propValue = z.getPropertyValue(prop); if (typeof propValue === "string" && propValue) { alreadyExistingProps[prop] = propValue; } } for (let i = 0; i < x.length; i++) { let prop = x.item(i); let propValue = x.getPropertyValue(prop); if (typeof propValue === "string" && propValue) { if (!alreadyExistingProps.hasOwnProperty(prop) || alreadyExistingProps[prop] !== propValue) { newStyle += prop + ": " + propValue + ";\n"; console.log(prop + ":" + propValue); } } } console.log("a"); newStyle += "\n}"; return newStyle; } var sheet = document.createElement("style"); sheet.innerHTML = build("txtBoxLikeStyle", "focus"); document.body.appendChild(sheet); sheet = document.createElement("style"); sheet.innerHTML = build("txtBoxLikeStyle", "active"); document.body.appendChild(sheet); sheet = document.createElement("style"); sheet.innerHTML = build("txtBoxLikeStyle", "hover"); document.body.appendChild(sheet); sheet = document.createElement("style"); sheet.innerHTML = build("txtBoxLikeStyle"); document.body.appendChild(sheet); });
HTML
<input id="t1" type="text" value="this is an iput element"> <p/> <div id="d1" class="txtBoxLikeStyle">this is a div element</div> <p/> The div copies the style of the input-text element, but as you can see, it looks pretty differnt ...
疑问
请问是我的代码存在问题,还是所有浏览器都存在此类缺陷?
注:我已对代码做了小幅调整,生成运行时样式时省略无用的CSS属性,但问题依旧,只是简化了分析部分。
内容的提问来源于stack exchange,提问作者user1470240
相关产品推荐
相关产品推荐

