2015-06-20 59 views
0

我有一個文本字段和解釋div。當我在文本字段中輸入內容時,是否可以讓這個解釋div具有不透明度= 0? 在此先感謝您的幫助。 下面是HTML代碼:Div opacity = 0只有當我在文本字段中鍵入東西

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

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

你想的不透明度爲零,如果有人打字,當有人輸入或在兩種情況下? –

回答

2

你可以只用CSS做,如果你設置的輸入爲required

<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/

0

你可以試試:

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

你應該給你的答案增加更多的解釋。這段代碼做了什麼?它如何回答這個問題?爲什麼OP會嘗試這個而不是原始代碼或任何其他答案? –

0

這將需要使用JavaScript來聽文本輸入和隱藏DIV。

示例使用jQuery:

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

CSS:

.hidden { 
    opacity: 0; 
} 

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

0

是,JavaScript是這裏不錯,雖然,功能保持屬於它的地方,對事件作出響應在CSS是可疑的做法。您需要按鍵事件進行輸入。單獨定義的功能使它們更易於重複使用。

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

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

see keypress example here

您可能會更好,雖然這樣做,因爲焦點和模糊將允許您當用戶移動上撤消效果。這裏也有一個演示功能。

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'); 
0

您可以使用此代碼:

<html> 
<head> 
    <title>Some title</title> 
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> 
    <script type='text/javascript'> 
     $(document).ready(function(){ 
      $('#searchdevice').blur(function(){ 
       $('#explain').fadeTo(1000, 0); 
      }); 
     }); 
    </script> 
</head> 
<body> 
<input type='text' name='input' id="searchdevice" class="search-field" placeholder="" autofocus/> 
<div id="explain">Search your device in the text field</div> 
</body> 
</html> 

在這裏,您可以嘗試通過fadeto從鏈接各種影響 - http://api.jquery.com/fadeTo/

相關問題