【问题标题】:Vertically aligning the text cursor (caret?) in an input box with jQuery, Javascript or CSS使用 jQuery、Javascript 或 CSS 在输入框中垂直对齐文本光标(插入符号?)
【发布时间】:2010-11-15 17:08:26
【问题描述】:

我在 CSS 中的输入框上弄乱了 CSS,以使文本变大、添加边框、更改颜色等。

我已经使用填充将较大的文本对齐(垂直对齐)在我的输入框中,但是闪烁的小文本光标非常对齐(拥抱底部)。我想知道是否有一种方法可以自行调整闪烁的文本光标而不会弄乱文本的位置。

谢谢! 马特

这是 CSS:

div#search_box {
    height:32px;
    width: 366px;
    float:left;
    margin-left:86px;
    margin-top:14px;
    background-color: #ffffff;
    border: 2px solid #b66b01;
}

input#search_input {
    border:none;
    position: relative;
    float: left;
    height: 32px;
    width: 335px;
    font-size: 18px;
    padding-top: 9px;
    padding-left: 4px;
    outline-style:none;
    font-family: Helvetica, Arial, "MS Trebuchet", sans-serif;
    color: #5a5a5a;
}

div#search_icon {
    width:22px;
    height:24px;
    float:right;
    margin-right:5px;
    margin-top:4px;
    cursor: pointer;
    background: url('images/magnifier.png');
}

HTML:

<div id="search_box">
     <input type="text" name="query" id="search_input" autocomplete="off"/>
     <div id="search_icon">
</div>

结果:

【问题讨论】:

  • 向我们展示代码会很有帮助。另外,这是否会在不同的浏览器中发生?
  • 嗯,它在其他浏览器中看起来不同,但它们看起来都不理想。这张图片来自火狐。
  • 哦天哪.. Ummm... 无论未定义的 DOCTYPE 是什么?为什么这是相关的? (我对这些东西的经验很少。)

标签: javascript jquery html css input


【解决方案1】:

您的问题是您在指定输入框的高度时没有考虑输入框的填充。

您指定的高度为 32 像素,但会添加任何填充,因此输入框的高度实际上是 32 + 9 + 4 = 45 像素。光标在 45px 高的输入框中垂直居中,但您的边框在 32px 高的 div 周围。将搜索输入中的 'height: 32px' 更改为 'height: 19px' 即可。

我(非常强烈)推荐使用Firebug。这对于弄清楚这些事情非常有用。

【讨论】:

    【解决方案2】:

    旁注:您不需要div#search_icon,您的输入可能具有以下背景:

      background: white url('images/magnifier.png') no-repeat right NNpx;
    

    【讨论】:

    • 哎呀。一个问题是不能再点击放大镜。它也可以用作“提交”按钮。
    【解决方案3】:

    看起来您并没有在示例中显示所有 css(是否有一两个 div 用作边框?),但是您是否尝试过删除 height 属性并将 padding-bottom 设置为padding-top 的值(9px)?

    【讨论】:

    • 我刚试过。移除了 padding-top、height,添加了 9px padding-bottom。它只会使所有文本和光标移到最顶部。
    • 仅删除 height 并在 input#search_input 类中同时包含 padding-bottom: 9pxpadding-top: 9px
    • 好的。是的,我的意思是插入符号移动,但文本也是如此。也许我只需要尝试不同的字体。我通常不会关心这类事情——但这种搜索就像网站的主要资产。
    猜你喜欢
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 2012-01-23
    • 2011-03-21
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多