创建一个canvas元素并使用jQuery设置它的width和height属性 [英] 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 <$ c $通过 $('element',{attributes})创建元素时,应将
和 height
)而不是CSS?
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(值)和 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
},
这篇关于创建一个canvas元素并使用jQuery设置它的width和height属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!