javascript - 使用简单的 javascript 或 jQuery 模拟选择中所选选项的文本对齐中心

标签 javascript jquery css select drop-down-menu

我想知道是否可以“模拟” 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/

相关文章:

javascript - jQuery 在 IE 上返回空输入值

CSS 在悬停时缓入缓出

css - Material-UI:如何防止 Grid 元素出现在下一行?

javascript - SharePoint Javascript - 选项卡绝对顶部;如何插入上面的图片?

javascript - 使用 Javascript 计算 <ul> 高度

php - 根据用户答案从数据库中选择宠元素种/汽车/自行车/等的算法

javascript - 如何让 require.context 在有/没有 Craco 的情况下与 Create React App 一起工作?

java - HtmlUnit 2.9 jar 执行 JavaScript

javascript - 使用 jQuery 替换 div 内容

Javascript: "No ' 请求的资源上存在 Access-Control-Allow-Origin' header 。因此不允许访问 Origin 'null'。 “