javascript的函数封装

代码如下:

function rotatePlusLink() {
            $(".linkDiv").each(function () {

                var tr = window.getComputedStyle($(this)[0], null).getPropertyValue("transform");

                if (tr == 'none') {
                    this.css('transform', 'scale(1) rotate(0deg)');
                    return;
                }

                var values = tr.split('(')[1].split(')')[0].split(',');
                var a = values[0];
                var b = values[1];
                var c = values[2];
                var d = values[3];

                var scale = Math.sqrt(a * a + b * b);

                var sin = b / scale;
                var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));

                this.style.transform = 'rotate(' + (angle + 5) + 'deg) scale(' + scale + ')';
            });
}


function rotateReduLink() {
            $(".linkDiv").each(function () {

                var tr = window.getComputedStyle($(this)[0], null).getPropertyValue("transform");

                if (tr == 'none') {
                    this.css('transform', 'scale(1) rotate(0deg)');
                    return;
                }

                var values = tr.split('(')[1].split(')')[0].split(',');
                var a = values[0];
                var b = values[1];
                var c = values[2];
                var d = values[3];

                var scale = Math.sqrt(a * a + b * b);

                var sin = b / scale;
                var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));

                this.style.transform = 'rotate(' + (angle - 5) + 'deg) scale(' + scale + ')';
            });
}

这两个函数中的linkDiv的设置 怎么能封装成一个函数调用啊? 这两个函数只有一个地方不一样 就是设置属性的那里,一个加号,一个减号。

看你的写法这两个函数应该是绑定在相应的标签上的这样的话你将这个操作符(+/-)作为一个参数直接传进来不就行了

function rotateLink(str){
....
if(("+").equals(str)){
this.style.transform = 'rotate(' + (angle + 5) + 'deg) scale(' + scale + ')';
}
if(("-").equals(str)){
this.style.transform = 'rotate(' + (angle - 5) + 'deg) scale(' + scale + ')';
}
...............
}

两个办法,一个加一个参数,这一行用if判断
一个是直接传入+ - 作为字符串,程序中用eval求值

//ES6 函数的解构赋值,赋初值5
function rotateLink(nums = 5) {
$(".linkDiv").each(function () {

            var tr = window.getComputedStyle($(this)[0], null).getPropertyValue("transform");

            if (tr == 'none') {
                this.css('transform', 'scale(1) rotate(0deg)');
                return;
            }

            var values = tr.split('(')[1].split(')')[0].split(',');
            var a = values[0];
            var b = values[1];
            var c = values[2];
            var d = values[3];

            var scale = Math.sqrt(a * a + b * b);

            var sin = b / scale;
            var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));

            this.style.transform = 'rotate(' + (angle + nums) + 'deg) scale(' + scale + ')';
        });

}
不推荐使用eval