[英]jQuery set custom dimensions for an element
我有一个div,我想用两个文本输入设置自定义尺寸。
<div id="theFrame"></div>
width: <input id="custWidth" type="text">
height: <input id="custHeight" type="text">
<br>
<button id="custSet">Set my width!</button>
我尝试用变量设置高度和宽度,但我现在不知道如何做到这一点。
var frame = $('div#theFrame');
$("#custWidth")
.keyup(function () {
var custWidth = $(this).attr('value');
})
.keyup();
$("#custHeight")
.keyup(function () {
var custHeight = $(this).attr('value');
})
.keyup();
$('#custSet')
.click( function() {
frame.css({height: custHeight, width: custWidth});
});
谢谢。
var frame = $('div#theFrame');
var custWidth;
var custHeight;
$("#custWidth").keyup(function () {
custWidth = $(this).attr('value');
}).keyup();
$("#custHeight").keyup(function () {
custHeight = $(this).attr('value');
}).keyup();
$('#custSet').click( function() {
frame.css({height: custHeight, width: custWidth});
});
您的变量范围已关闭。
您的问题是宽度和高度范围的变量。 您需要在事件处理程序之外定义它们,然后在它们之前设置它们而不使用var
。
在外部范围内声明您的变量:
var frame = $('div#theFrame');
var custWidth = 40; // declared outside and assigned a default value
var custHeight = 40; // declared outside and assigned a default value
$("#custWidth").keyup(function () {
custWidth = $(this).attr('value');
}).keyup();
$("#custHeight").keyup(function () {
custHeight = $(this).attr('value');
}).keyup();
$('#custSet').click( function() {
//frame.height(custHeight); // Alternative to .css() if you like, also doesn't need 'px' as it always is in pixels.
//frame.width(custWidth); // Alternative to .css() if you like, also doesn't need 'px' as it always is in pixels.
frame.css({height: custHeight, width: custWidth});
});
在设置CSS时,您可能需要包含'px':
frame.css({height: custHeight + 'px', width: custWidth + 'px'});
此外,您需要全局定义custHeight和custWidth参数,因为它们仅在key up函数中是本地的。
var frame = $('div#theFrame'), custWidth = 0, custHeight = 0;
$("#custWidth")
.keyup(function () {
window.custWidth = $(this).attr('value');
})
.keyup();
而且......我相信你不需要第二次keyup()调用:
$("#custWidth")
.keyup(function () {
window.custWidth = $(this).attr('value');
});
只需将两个变量设为全局custWidth,即custHeight
var frame = $('div#theFrame');
var custWidth,custHeight ;
$("#custWidth").keyup(function () {
custWidth = $(this).attr('value');
}).keyup();
$("#custHeight").keyup(function () {
custHeight = $(this).attr('value');
}).keyup();
$('#custSet').click( function() {
frame.css({height: custHeight, width: custWidth});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.