Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

javascript - Creating a canvas element and setting its width and height attributes using 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>

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.

I do know I could just do:

var newCanvas = $('<canvas/>',{'class':'radHuh'}).attr({'width':100,'height':200});

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

jQuery try to match each attribute name with a jQuery function name. Matched functions are called.

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) and height(value) functions set CSS width and height of an element.


Relevant jQuery source code line (https://github.com/jquery/jquery/blob/master/src/attributes.js#L308)

if ( pass && name in jQuery.attrFn ) {

attrFn object definition (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
},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...