使用 jQuery 创建画布元素并设置其宽度和高度属性 [英] Creating a canvas element and setting its width and height attributes using jQuery
问题描述
我只是想在 jQuery 中执行以下操作:
I was just trying to do the following in jQuery:
var newCanvas = $('<canvas/>',{'width':100,'height':200,'class':'radHuh'});
$(body).append(newCanvas);
这是有效的(有点)并生成以下标记:
This is working (kind of) and generates the following markup:
<canvas style="width:100px; height:200px;" class="radHuh"></canvas>
你们中的大多数人可能都知道 canvas
元素并不真正喜欢 CSS 尺寸,但需要一个 width 和 height 属性,所以这个对象创建对我来说失败了.
As most of you might know canvas
elements don't really like CSS dimensions but expect a width and height attribute, so this object creation failed for me.
我知道我可以做到:
var newCanvas = $('<canvas/>',{'class':'radHuh'}).attr({'width':100,'height':200});
相反,但我只是想知道是否有任何方法可以告诉 jQuery 在通过 创建元素时
而不是 CSS?width
和 height
应该被视为属性$('element',{attributes})
instead, but I was just wondering nonetheless if there is any way of telling jQuery that width
and height
should be treated as attributes when creating the element via $('element',{attributes})
and not as CSS?
推荐答案
jQuery 尝试将每个属性名称与 jQuery 函数名称匹配.调用匹配的函数.
jQuery try to match each attribute name with a jQuery function name. Matched functions are called.
width
和 height
是 jQuery 函数,所以你的原始代码是这样的:
width
and height
are jQuery functions, so your original code is equivalent to this:
var newCanvas =
$('<canvas/>',{'class':'radHuh'})
.width(100)
.height(100);
width(value) 和 height(value) 函数设置CSS 元素的宽度和高度.
width(value) and height(value) functions set CSS width and height of an element.
相关的jQuery源代码行(https://github.com/jquery/jquery/blob/master/src/attributes.js#L308)
Relevant jQuery source code line (https://github.com/jquery/jquery/blob/master/src/attributes.js#L308)
if ( pass && name in jQuery.attrFn ) {
attrFn
对象定义(https://github.com/jquery/jquery/blob/master/src/attributes.js#L288):
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
这篇关于使用 jQuery 创建画布元素并设置其宽度和高度属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!