强制显示输入框工具提示/标题

Force input box tooltip/title to appear

本文关键字:工具提示 标题 输入 显示      更新时间:2023-09-26

首先,我没有使用jQuery,我想知道是否有任何方法强制输入框工具提示出现。(我想用这个工具提示告诉用户输入另一个用户名和/或密码是不可接受的。)

function change(){
    if (document.getElementById('myTextField').value.length < 5){
        alert('show the tooltip in this case ');
    }
}
#myTextField{
    
}
<input type="text" id="myTextField"/>
<input type="submit" id="myButton" value="click me !" onclick="change()"/>

正如@Roope在上面的评论中提到的,你可以使用data元素和CSS伪元素。

data元素可以被javascript和CSS访问。但是在CSS中(到目前为止),你只能在伪元素::after::beforecontent属性中访问它,这足以管理工具提示(几乎)只在CSS

注:该代码仅在Chrome上测试(过渡属性可能需要其他浏览器的前缀)

function change(){
    document.getElementById('myTooltip').style.opacity = '1';
    if (document.getElementById('myTextField').value.length < 5){
        document.getElementById('myTooltip').setAttribute('data-tooltip', 'tooltip text');
    }
}
function keyPress(){
    document.getElementById('myTooltip').style.opacity = '0';
}
#myTooltip {
  position: relative;
  opacity: 0;
  transition: opacity .3s;
}
#myTooltip:before {
  position: absolute;
  top: 180%;
  width:160px;
  margin-bottom: 5px;
  margin-left: 5px;
  padding: 7px;
  background-color: #000;
  color: #fff;
  content: attr(data-tooltip);
  text-align: center;
  font-size: 14px;
  border-radius: 5px;
  line-height: 1.2;
}
#myTooltip:after {
  position: absolute;
  top: 155%;
  left: 85px;
  margin-left: -5px;
  width: 0;
  border-bottom: 5px solid #000;
  border-right: 5px solid transparent;
  border-left: 5px solid transparent;
  content: "";
  font-size: 0;
  line-height: 0;
}
<span id="myTooltip"></span>
<input type="text" id="myTextField" onkeyup="keyPress()"/>
<input type="submit" id="myButton" value="click me !" onclick="change()"/>