2011-07-27 112 views
0

我已經得到了這個與起點作爲一個跨度的工作,但我想要的形式仍然功能,如果在瀏覽器this is how I had it working原來禁用javascript。我還是很新的javascript,請有人幫忙。使用JavaScript來展示一個表單字段作爲文本,直到點擊

window.onload = function() { 

    document.getElementById('container').onclick = function(event) { 
var span, input, text; 

// Get the event (handle MS difference) 
event = event || window.event; 

// Get the root element of the event (handle MS difference) 
span = event.target || event.srcElement; 

// If it's a span... 
if (span && span.tagName.toUpperCase() === "SPAN") { 
    // Hide it 
    span.style.display = "none"; 

    // Get its text 
    text = span.innerHTML; 

    // Create an input 
    input = document.createElement("input"); 
    input.type = "text"; 
    input.size = Math.max(text.length/4 * 3, 4); 
    span.parentNode.insertBefore(input, span); 

    // Focus it, hook blur to undo 
    input.focus(); 
    input.onblur = function() { 
    // Remove the input 
    span.parentNode.removeChild(input); 

    // Update the span 
    span.innerHTML = input.value; 

    // Show the span again 
    span.style.display = ""; 
     }; 
    } 
    }; 
}; 

回答

0

使用readonly屬性在input元素:

<input type="text" readonly /> 

,然後刪除該屬性用JavaScript的onclick事件處理程序,重新分配它blur

var inputs = document.getElementsByTagName('input'); 

for (i=0; i < inputs.length; i++) { 
    inputs[i].setAttribute('readonly',true); 
    inputs[i].onclick = function(){ 
     this.removeAttribute('readonly'); 
    }; 
    inputs[i].onblur = function(){ 
     this.setAttribute('readonly',true); 
    }; 
} 

JS Fiddle demo

+0

除非我失去了一些東西,這將使形式無用的,如果JavaScript是禁用 –

+0

@Philbert:哎呀。我更正了JavaScript,所以'readonly'被應用,刪除,並且被JavaScript重新應用,而不是在HTML中設置。不過,你是對的,但最初這個答案會是非JS不友好......哎呀。 =/ –

+0

我不會有太多的運氣。 [這是我的測試頁面](http://pastebin.com/gJWEdPNq),我可以得到一個白癡檢查,這裏遲到了。 –

0

然後,只需從開始處將輸入字段放在那裏,並使用在窗體加載時運行的腳本來隱藏它們。這樣,如果Javascript不受支持,所有的字段都將可見。

+0

這就是我想要做的,但不知道如何,上面的代碼塊是由其他人編寫的,我一直在努力向後工作,但沒有任何運氣 –

1

最好的辦法是首先顯示輸入,然後在頁面加載時迅速將其交換出來,然後在用戶單擊時將其交換回去。

您也可以考慮在整個時間使用表單元素,但只是改變它的CSS類,使其看起來像普通文本。這將使您的界面更清潔並且更容易在將來進行維護。

0

我認爲你最好的選擇是用noscript標籤打包表格,當瀏覽器禁用Javascript時,這些標籤將被觸發。如果他們甚至在noscript標籤中顯示,那麼只需將它們設置爲不可見的Javascript。

0

如果你有jQuery,像這樣的東西應該工作。

function makeElementIntoClickableText(elm){ 
    $(elm).parent().append("<div onClick='switchToInput(this);'>"+ elm.value +"</div>"); 
    $(elm).hide(); 
} 

function switchToInput(elm){ 
    $(elm).prev().prev().show(); 
    $(elm).hide(); 
} 

makeElementIntoClickableText($("input")[0]); 
相關問題