2016-01-14 77 views
4

我做了一些方案,其中只要檢測到的文本它需要做的事情的輸入變化。但它不適合我。所以我改變我開始給控制檯上的值來驗證它,只要它檢測到輸入變化,它總是返回undefined。 如何獲取用戶輸入的像素大小的文字?滾動寬度總是返回undefined

<!doctype html> 
<html> 
<head> 
<style> 
    input[type=text] { 
     height: 20px; 
     width: 100px; 
    } 
</style> 
<script src="jquery.js"></script> 
</head> 
<body> 
    <input type="text" id="func"></input> 
</body> 
<script> 
    $("#func").change(function() { 
     console.log($("func").scrollWidth); 
    }); 
</script> 
</html> 

回答

2

你的代碼中有兩個bug。首先,選擇沒有散列的元素func。如果您在jQuery中選擇了一個ID,則需要在ID名稱前面使用#(請參閱reference)。所以,你需要像這樣選擇它:$('#func')。其次,您需要$('#func')的DOM元素,而不是其jQuery包裝來訪問屬性scrollWidth。您可以使用$('#func')[0].scrollWidth$('#func').get().scrollWidth來完成此操作。

但是,我會建議您使用jQuery width function來獲得輸入字段的寬度:$('#func').width()

+0

我需要輸入沒有全尺寸輸入框的像素的大小? –

+0

沒有這樣的函數可用於獲取輸入字段內容的寬度。然而有一些approches這裏:http://stackoverflow.com/questions/3392493/adjust-width-of-input-field-to-its-input這裏:http://stackoverflow.com/questions/9328682/jquery -resizing形式輸入爲基礎的上值寬度 –

0

scrollWidth是DOM-元屬性,而不是一個jQuery屬性,$('#func').get().scrollWidth加以界定。