2013-01-09 18 views
1

我想有一些工作就像在Windows Live上的登錄框。我在裏面看到標籤的盒子,然後標籤在用戶開始輸入時消失。我在哪裏可以找到一個CSS/JavaScript解決方案來在輸入字段中佔位符標籤?

我能找到的是使用jQuery的解決方案。有誰知道一些JavaScript/CSS解決方案,不需要我加載jQuery?我的意思是HTML5中的佔位符屬性以外的其他內容。我想要一些能在大多數瀏覽器中工作的東西,而不僅僅是新的東西。

+2

*大多數*瀏覽器支持'placeholder'實際上:http://caniuse.com/#search=placeholder –

+0

IE <10仍具有相當可敬[分享](http://gs.statcounter.com/#browser_version_partially_combined-ww-monthly-201301-201301-bar)。謝天謝地,這似乎正在快速改善。 – RichardTowers

回答

0

你可以推出自己的...這是一個JSFiddle我通過在一起。 http://jsfiddle.net/VF8Dr/

CSS

.placeholder { 
    color: gray; 
    position: absolute; 
    padding-left: 10px; 
} 

JS

function addPlaceholder(id, text) { 
    var elm = document.getElementById(id); 
    var ph = document.createElement("SPAN"); 
    ph.className = "placeholder"; 
    ph.innerHTML = text; 
    elm.parentNode.insertBefore(ph, elm.nextSibling); 
    ph.style.left = elm.offsetLeft + 'px'; 
    ph.style.top = elm.offsetTop + 'px'; 
    ph.onclick = function() { 
    ph.style.display = 'none'; 
    elm.focus(); 
    }; 
    elm.onfocus = function() { 
    if(ph.style.display != 'none') 
     ph.style.display = 'none'; 
    }; 
    elm.onblur = function() { 
    if(elm.value == '') 
     ph.style.display = ''; 
    }; 
} 
addPlaceholder("demo", "my text"); 

很顯然,這不是廣泛的測試,但如果你固執不使用像jQuery框架(或只是避免不必要的膨脹),但仍希望跨瀏覽器和舊瀏覽器的兼容性,這將幫助你到達那裏。

0

這是我在過去使用:

activatePlaceHolder: function() { 
    var detect = navigator.userAgent.toLowerCase(); 
    if (detect.indexOf("msie") < 0) return false; 
    var inputs = document.getElementsByTagName("input"); 
    var inputLen = inputs.length; 
    for (var i = 0; i < inputLen; i++) { 
     if (inputs[i].getAttribute("type") == "text") { 
      if (inputs[i].getAttribute("placeholder") && inputs[i].getAttribute("placeholder").length > 0) { 
       inputs[i].value = inputs[i].getAttribute("placeholder"); 
       inputs[i].onclick = function() { 
        if (this.value == this.getAttribute("placeholder")) { 
         this.value = ""; 
        } 
        return false; 
       } 
       inputs[i].onblur = function() { 
        if (this.value.length < 1) { 
         this.value = this.getAttribute("placeholder"); 
        } 
       } 
      } 
     } 
    }  
} 
+0

您可能還需要在表單提交上添加一個事件以清除任何佔位符作爲值的文本框。 –

相關問題