Creating a canvas element and setting its width and height attributes using jQuery

后端 未结 6 1749
天涯浪人
天涯浪人 2020-12-16 09:55

I was just trying to do the following in jQuery:

var newCanvas = $(\'\',{\'width\':100,\'height\':200,\'class\':\'radHuh\'});
$(body).append(n         


        
6条回答
  •  攒了一身酷
    2020-12-16 10:27

    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 = 
        $('',{'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
    },
    

提交回复
热议问题