我想知道是否可以“模拟” text-align: center;通过使用父容器和简单的 javascript(或 jQuery)脚本进行选择(具有跨浏览器兼容性)。我希望无需安装 js 库即可完成此操作,因此需要一个简单的脚本。
目标:无论屏幕宽度如何,选择任一选项时,使文本相对于外部(点)容器居中。我只想将其用于所选值(即有效占位符),我不担心选项下拉列表的格式。
这需要一个 JavaScript 答案 - 不能纯粹在 CSS 中完成
https://jsfiddle.net/zs0or8et/1/
<div>
<select>
<option>Longtextoption</option>
<option>Short</option>
</select>
</div>
<style>
div {
width:100%;
outline: 1px dotted;
}
select {
margin-left:50%;
outline:none;
border:none;
background:none;
-webkit-appearance: none;
-moz-appearance: none;
/* BELOW TRANSLATION NEEDS TO BE MADE DYNAMIC DEPENDING ON WIDTH OF SELECTED OPTION */
transform: translate(-50px);
}
</style>
最佳答案
您对使用另一个 div 来保存您的值有何看法?
HTML
<div class="wrapper">
<select onchange="change(this)">
<option value="-1">Please Select</option>
<option value="0">Scotty Auten</option>
<option value="1">Adriane Gaillard</option>
<option value="2">Tequila Goodnough</option>
</select>
<div id="value" aria-hidden="true" tabindex="-1">Please Select</div>
</div>
CSS
.wrapper {
width: 100%;
position: relative;
}
#value {
position: absolute;
top: 0;
left: 0;
text-align: center;
width: 100%;
font-family: inherit;
font-size: inherit;
line-height: inherit;
background: transparent;
pointer-events: none;
}
select {
width: 100%;
font-family: inherit;
font-size: inherit;
line-height: inherit;
appearance: none;
-moz-appearance: none;
-webkit-appearance: none;
border: 1px solid #999;
color: white;
text-color: white;
margin: 0;
}
option {
color: black;
text-color: black;
}
JS
function change(item) {
var name = item.options[item.selectedIndex].text
document.getElementById("value").innerHTML = name;
}
我们使用 aria 隐藏来隐藏屏幕阅读器的值 div。
关于javascript - 使用简单的 javascript 或 jQuery 模拟选择中所选选项的文本对齐中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61678529/