仅当我在文本字段中键入内容时,Div opacity = 0

时间:2015-06-20 13:23:45

标签: html opacity

我有一个文本字段和一个解释div。只有当我在文本字段中输入内容时,才能使此解释div具有opacity = 0吗? 在此先感谢您的帮助。 这是HTML代码:

<input type='text' name='input' id="searchdevice" class="search-field"  placeholder="" autofocus/>

<div id="explain">
            Search your device in the text field
            </div>

6 个答案:

答案 0 :(得分:2)

如果将输入设置为required

,则只需使用CSS即可
<input type='text' name='input' id='searchdevice' class='search-field' required='required' autofocus />

<div id='explain'>
    Search your device in the text field
</div>

CSS:

/* Show by default */
#explain {
    opacity: 1;
}

/* Hide it when input field has content */
#searchdevice:valid + #explain {
    opacity: 0;
}

/* Remove "invalid" styling when input field is empty.
E.g. in Firefox, the input has a red box-shadow by default. */
#searchdevice:invalid {
    box-shadow: none;
}

当您在输入字段中输入内容时,它会“有效”,#explain的不透明度为0。

:valid选择器的浏览器支持:http://caniuse.com/#feat=form-validation

演示:https://jsfiddle.net/2ozh40vp/1/

答案 1 :(得分:0)

您可以尝试:

$('#searchdevice').on('input', function(){
    $('#explain').css('opacity', 0);
});

答案 2 :(得分:0)

这将需要JavaScript来监听文本输入并隐藏DIV。

使用jQuery的示例:

$('#searchdevice').on('input', function(){
    $('#explain').addClass('hidden');
});

的CSS:

.hidden {
    opacity: 0;
}

工作小提琴:http://jsfiddle.net/spanndemic/kphgg2d0/

答案 3 :(得分:0)

是的,javascript在这里很好,功能保留在它所属的位置,响应css中的事件是有问题的做法。您需要按键事件才能输入。单独定义的功能使它们更容易重复使用。

var hideExplain = function() {
    document.getElementById('explain').style.opacity='0';
}

document.getElementById('searchdevice').addEventListener("keypress", hideExplain);

see keypress example here

你可能会做得更好,因为焦点和模糊将允许你在用户移动时撤消效果。这里也有一个show功能。

var showExplain = function() {
    document.getElementById('explain').style.opacity='1';
}

document.getElementById('searchdevice').addEventListener("focus", hideExplain);
document.getElementById('searchdevice').addEventListener("blur", showExplain);

see the example here

你可以使用按键来移除尖端并模糊以重新显示它,这样尖端会为用户尽可能长时间地徘徊。 See anothe example

此外,您会发现更好添加和删除类 - 这是一个使用JQuery的示例。现在您的样式类也可以重复使用。

CSS

.is-transparent {
    opacity: 0;
}

.is-opaque {
    opacity: 1;
}

JQuery的

$('#explain').removeClass('is-opaque').addClass('is-transparent');

答案 4 :(得分:0)

你只需要这个css行:

input:focus + #explain{opacity:0}

http://jsfiddle.net/kLLkyvyh/

答案 5 :(得分:0)

您可以使用以下代码:

fadeto

您可以在此处通过up_down

链接up_down尝试各种效果