22

Firefox で JavaScript を使用して CSS グラデーションを編集する作業を行っています。ユーザーが入力できる入力ボックスがあります 1. 方向 2. 1 番目の色 3. 2 番目の色

ここにhtmlがあります

<html>
    <head>
        <title>Linear Gradient Control</title>
        <script>
            function renderButton(){ 
            var orientation = document.getElementById("firstValue").value;
            var colorOne = document.getElementById("firstColor").value;
            var colorTwo = document.getElementById("secondColor").value;
            //alert(orientation);
            //alert(colorOne);
            //alert(colorTwo);

            };
        </script>
        <style>
            #mainHolder
            {
            width:500px;
            background: -moz-linear-gradient(left,  green,  red);

            }
        </style>
    </head>
    <body>
        <h1>Gradient Editor</h1>
        <form>
            <input type="text" id="firstValue">orientation</input><br />
            <input type="text" id="firstColor">first color</input><br />
            <input type="text" id="secondColor">second color</input><br />
        </form>
        <button type="button" onclick="renderButton()">Render</button>
        <div id="mainHolder">Content</div>
    </body>
</html>

要約すると、ユーザーは 3 つの値を指定し、関数「renderButton();」に渡されます。ユーザーが独自のカスタム グラデーション ボックスを作成できるように、CSS3 グラデーションの 3 つの値を変更するには、どの行を使用できますか? 必要なのは1行か2行だけだと思います。

PS この例は Firefox でのみ機能することを認識しています。さまざまなブラウザーで作業する前に、概念を理解したいだけです。

4

1 に答える 1

33

次のようなものから始めます。

var dom = document.getElementById('mainHolder');
dom.style.backgroundImage = '-moz-linear-gradient('
        + orientation + ', ' + colorOne + ', ' + colorTwo + ')';

Firefox よりも多くのブラウザーをサポートする必要がある場合は、ブラウザー スニッフィングまたは Modernizr のような機能検出と組み合わせて行う必要があります。

以下は、Modernizr (Firefox、Chrome、Safari、Opera でテスト済み) と同様の機能検出を使用して、これを行う方法の例です。

// Detect which browser prefix to use for the specified CSS value
// (e.g., background-image: -moz-linear-gradient(...);
//        background-image:   -o-linear-gradient(...); etc).
//

function getCssValuePrefix()
{
    var rtrnVal = '';//default to standard syntax
    var prefixes = ['-o-', '-ms-', '-moz-', '-webkit-'];

    // Create a temporary DOM object for testing
    var dom = document.createElement('div');

    for (var i = 0; i < prefixes.length; i++)
    {
        // Attempt to set the style
        dom.style.background = prefixes[i] + 'linear-gradient(#000000, #ffffff)';

        // Detect if the style was successfully set
        if (dom.style.background)
        {
            rtrnVal = prefixes[i];
        }
    }

    dom = null;
    delete dom;

    return rtrnVal;
}

// Setting the gradient with the proper prefix
dom.style.backgroundImage = getCssValuePrefix() + 'linear-gradient('
        + orientation + ', ' + colorOne + ', ' + colorTwo + ')';
于 2013-02-25T16:16:01.087 に答える