javascript - 如何在输入文本的正下方添加 div?

标签 javascript jquery html

我想开发我的简单自动完成功能,我对 JQuery 自动完成插件不感兴趣。

我只是想在输入文本的正下方添加一个潜水,这段代码应该可以工作,我做错了什么?实现它的方法是什么?

JSFiddle

如果你不想打开 fiddle ,这里是代码:

$("#txtSearch").keypress(function (e) {
    if ($("#txtSearch").val().length >= 2) {
        var pos = $("#txtSearch").position();
        $('<div />', {
            'html': "xxxxxxxxx  xx  x"
        }).css({
            top: pos.top,
            left: pos.left,
            width: '300px',
            position: 'absolute',
            'background-color': 'Yellow'
        }).appendTo($("#txtSearch"));
    }
});

最佳答案

试试下面的代码,

$("#txtSearch").keypress(function (e) {
   if ($("#txtSearch").val().length >= 2) {
      var pos = $("#txtSearch").position();
      $('<div />')
      .html("xxxxxxxxx  xx  x")
      .css({
         top: pos.top + $("#txtSearch").height()  + 1,
         left: pos.left,
         width: '300px',
         position: 'absolute',
         'background-color': 'Yellow'
      }).insertAfter($("#txtSearch"));
   }
});

演示: http://jsfiddle.net/uZF5g/1/

关于javascript - 如何在输入文本的正下方添加 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14862494/

相关文章:

javascript - 是否有另一种方法可以在此函数之外关闭 MongoDB 连接?

iphone - "Legality"在 UIWebView/Phonegap 中使用 web 资源和 appcache

javascript - 谷歌浏览器中的垂直滚动错误

javascript - D3 强制布局,较大的节点聚集在中心

javascript - React 路由器全局 header

javascript - 当用户完成输入时运行 JS 代码

javascript - PHP Populate dropdown with ajax onchange issue 仅限 IE

javascript - jquery - 获取 URL 路径的中间部分

javascript - jQuery Ajax 传递带有预定义变量的数组

html - 将容器缩小到图像宽度