1

box-shadow 有这样的语法

box-shadow: h-shadow v-shadow blur spread color inset;

我想设置一个 jQuery 函数,每次单击按钮时将 h-shadow、v-shadow 和模糊增加 2px。它会是什么样子?

$('button[type=submit]').bind('click': function(){
                                   $('div').css('box-shadow'???, '+=2');
})
4

2 回答 2

3

你可以试试:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <style type="text/css">
    #test{ box-shadow: 2px 2px 2px; width: 100px; height: 100px;}
    button{ height: 20px; width: 100px}
    </style>
    <script type="text/javascript">
    $(document).ready(function() {
        $("button").click(function(){
            $("#test").css('box-shadow', incValues($("#test").css('box-shadow')));
        });
    });

    function incValues(values){
        var splits = values.split('px');
        splits[0] = splits[0].split(' ');
        splits[0] = splits[0][splits[0].length-1];
        return (parseInt(splits[0])+2) +'px ' + (parseInt(splits[1])+2) +'px ' + (parseInt(splits[2])+2) +'px ';
    }
    </script>
</head>
<body>
    <div id='test'></div>
    <br/>
    <button>Test</button>
</body>
</html>
于 2013-07-01T03:08:40.557 回答
2

你可以通过使用几个正则表达式来获取颜色、hshadow、vshadow、模糊、展开以及它是否是插入的。一旦你得到它,你可以简单地将它增加 2。把它们放在一起并应用到按钮上。

这是更新的 jsfiddle(使用从原始 box-shadow CSS 获得的颜色和插入值。这是它的外观(更新):

var pattern = /\d+px/g;    //will match only those values with a number + px
var colorPattern = /rgb\(.+\)/;  //regex to get the color
var incr = 2;
$('#btn').bind('click', function(){
    var currentBoxShadowCSS = $(this).css('box-shadow');
    var color = currentBoxShadowCSS.match(colorPattern)[0];
    /*
    That will get us the color:
    rgb(255, 0, 0)
    */
    var matchesArr = $(this).css('box-shadow').match(pattern);   
    /* 
    That will return ["0px", "0px", "5px", "0px"] 
    That s basically [h-shadow, v-shadow, blur, spread]
    We are concerned with only the first 3
    */
    var oldHShadow = matchesArr[0].split('px')[0];
    var newHShadow = parseInt(oldHShadow, 10) + incr;

    var oldVShadow = matchesArr[1].split('px')[0];
    var newVShadow = parseInt(oldVShadow, 10) + incr;

    var oldBlur = matchesArr[2].split('px')[0];
    var newBlur = parseInt(oldBlur, 10) + incr;

    //check if this was an inset shadow
    var inset = currentBoxShadowCSS.indexOf('inset') > -1 ? ' inset': '';
    //we got what we need, apply it
    $(this).css('box-shadow', newHShadow + 'px ' + newVShadow + 'px ' + newBlur + 'px ' + color + inset);
});
于 2013-07-01T02:51:32.903 回答