2013-02-25 2 views
8

Firefox의 JavaScript를 통해 CSS 그래디언트를 편집하고 있습니다. 나는 사용자가JavaScript를 사용하여 CSS 그래디언트 편집

<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> 

그래서 요약하자면, 사용자가 자신의 세 값을 지정합니다 1. 방향 2. 1 컬러 3. 2 컬러 여기

는 HTML입니다 넣을 수있는 입력 상자가 , 이는 'renderButton();'함수에 전달됩니다. 사용자가 자신의 맞춤형 그래디언트 상자를 만들 수 있도록 CSS3 그래디언트의 3 가지 값을 변경하는 데 사용할 수있는 라인은 무엇입니까? 나는 내가 필요로하는 그 한두 줄만 추측하고있다.

P. 이 예제는 Firefox에서만 작동합니다. 다른 브라우저에서 작업하기 전에 개념을 이해하기 만하면됩니다. 다음과 같은 뭔가

답변

17

시작 : 파이어 폭스보다 더 많은 브라우저를 지원해야하는 경우

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

,이 브라우저 스니핑 또는 일부 모더 나이저 같은 특징 검출 중 하나와 함께 수행해야합니다.

다음은 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 + ')'; 
+0

나는 그것이 쉽지 않다는 것을 깨달았다. 정말 고맙습니다! – onTheInternet

+1

@ user2070478 : 다른 브라우저를 지원하는 방법의 예를 추가했습니다. IE9 이전 버전은 그라디언트를 지원하지 않습니다. 또한 초기 버전의 웹킷에는이 구문에서 다루지 않는 다른 구문이 있습니다. –

+0

당신은 이틀 전에 제 질문에 대답했습니다. 그러나 나는 여전히이 대답을 upvote 할 것입니다. 고맙습니다! – onTheInternet

관련 문제