首页 > 【javascript】 selection.width || 1 这是什么意思? 谢谢

【javascript】 selection.width || 1 这是什么意思? 谢谢

imgAreaSelect插件中的var scaleX = 100 / (selection.width || 1);
其中,selection.width || 1 这是什么意思?

marginLeft与margin-left一样吗?

这里 marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',为什么要求反?

谢谢

function preview(img, selection) {
    var scaleX = 100 / (selection.width || 1);
    var scaleY = 100 / (selection.height || 1);
  
    $('#ferret + div > img').css({
        width: Math.round(scaleX * 400) + 'px',
        height: Math.round(scaleY * 300) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
    });
}

$(document).ready(function () {
    $('<div><img src="ferret.jpg" style="position: relative;" /><div>')
        .css({
            float: 'left',
            position: 'relative',
            overflow: 'hidden',
            width: '100px',
            height: '100px'
        })
        .insertAfter($('#ferret'));

    $('#ferret').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview });
});

先对||前面的进行布尔运算,如果结果是true(即width存在且不是0),就使用width,否则使用||后的变量(1)


selection.width || 1 这是什么意思?
var scaleX = 100 / (selection.width || 1); 的意思就是先检查 selection.width 有没有值,有的话就用 100 / 该值再付给 scaleX,没的话就用 100 / 1 来赋值;

marginLeft与margin-left一样吗?
两者用的地方不同,在 jQuery 的 css 方法里用前者,后者用在 css 代码中

这里 marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',为什么要求反?
正是左边距增大,反是左边距减小

希望有所帮助~ :)

【热门文章】
【热门文章】