javascript - 当用户在文本区域中输入文本时显示/隐藏 div?

标签 javascript

我正在尝试切换 div,以便当用户在文本区域中输入文本时它会显示和隐藏。 我正在使用下面的代码,但它对我不起作用,任何人都可以告诉我为什么吗?谢谢

html:

<head>
<script>
$(document).ready(function() {
   $("#cname").keyup(function() {
        if ($("#cname").val() > 8) {
             $('#cname2').toggle("slow");
        }
   });
});
</script>

</head>

<form>

<input type="text" id="cname" name="cname" class="field">
<div id="cname2"></div>
</form>

CSS:

#cname2{
width:30px;
height:30px;
position:absolute;
margin-top:-13px;
margin-left:400px;
background-image: url('tick.png');
background-repeat:no-repeat;
background-position:right;
display:none;

} 

所以显然我上面的代码在 IE 9 中不起作用,但我应该能够通过使用此代码来实现我想要做的事情,但是有人可以告诉我我将 div ID 放在哪里/如何适应它为我工作?

var activeElement = null;
var activeElementValue = null;

// On focus, start watching the element
document.addEventListener("focusin", function(e) {
    var target = e.srcElement;
    if (target.nodeName !== "INPUT") return;

    // Store a reference to the focused element and its current value
    activeElement = target;
    activeElementValue = target.value;

    // Listen to the propertychange event
    activeElement.attachEvent("onpropertychange", handlePropertyChange);

    // Override .value to track changes from JavaScript
    var valueProp = Object.getOwnPropertyDescriptor(
            HTMLInputElement.prototype, 'value');
    Object.defineProperty(activeElement, {
        get: function() { return valueProp.get.call(this); },
        set: function(val) {
            activeElementValue = val;
            valueProp.set.call(this, val);
        }
    });
});

// And on blur, stop watching
document.addEventListener("focusout", function(e) {
    if (!activeElement) return;

    // Stop listening to propertychange and restore the original .value prop
    activeElement.detachEvent("onpropertychange", handlePropertyChange);
    delete activeElement.value;

    activeElement = null;
    activeElementValue = null;
});

function handlePropertyChange(e) {
    if (e.propertyName === "value" &&
            activeElementValue !== activeElement.value) {
        activeElementValue = activeElement.value;
        // Fire textchange event on activeElement
    }
};

最佳答案

$(document).ready(function() {
       $("#cname").keyup(function() {
            if ($("#cname").val().length > 8) {
                $('#cname2').show();
            } else {
                $('#cname2').hide();
            }
       });
    });

关于javascript - 当用户在文本区域中输入文本时显示/隐藏 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22784077/

相关文章:

javascript - Vue点击时切换按钮的颜色和文本

javascript - 什么是 JSON 缩进级别约定?

javascript - jQuery,获取和设置标签值

javascript - 使用 Object.keys() 与 Object.values() 从对象属性创建数组

javascript - 像饼图一样裁剪图像

自执行 block 中的 Javascript 函数无法访问。为什么?

javascript - AngularJS - 带有动态模板的指令

javascript - 两个 onclick 函数中哪个函数首先起作用

javascript - 如何将 dojo.connect 代码从 Dojo 1.3.1 迁移到 1.9.3

javascript - 无法将 JQuery Datepicker 与 asp 绑定(bind) :TextBox in sharepoint