2013-10-31 2 views
0

하나의 특정 페이지에 특정 요소를 집중시켜야합니다. 이런 경우 CSS를 사용하려고하면 다음과 같이됩니다.내 JavaScript에 CSS 적용

#returning_user_search_box { 
    position:absolute !important; 
    width:50% !important; 
    height:300px !important; 
    left:0 !important; 
    right:0 !important; 
    margin:auto !important; 
} 

내 요소는 내 필요에 따라 잘 정렬됩니다. 문제는 내 요소가 특정 스타일을 적용 할 필요가없는 다른 페이지도 존재한다는 것입니다. 그래서 이런 자바 스크립트를 사용하려고했습니다 :

if (window.location.href.indexOf('specific_page.php') != -1) { 
    var style = document.getElementById('returning_user_search_box').style; 
    style.position  = 'absolute'; 
    style.right  = '0'; 
    style.left   = '0'; 
    style.width  = '50%'; 
    style.height  = '300px'; 
    style.margin  = 'auto'; 
} 

여기는 내 요소가 중심에 있지 않습니다. 왜 그런지 모르겠습니다. 나는 "중요하다!"를 추가하는 것이 가능한지 보았다. 자바 스크립트에서 속성을하지만 그것은 불가능한 것 같습니다.

정확히 내가 제어하는 ​​원격 서버에 있기 때문에 페이지의 html에 액세스 할 수 없습니다. JS 또는 CSS와 만 상호 작용할 수 있습니다.

당신은 페이지 별 상위 선택 포함하도록 CSS 선택기를 수정할 수 있습니다
+0

클래스를 사용하십시오. 또한 JS와 CSS는 어떻게 변경할 수 있습니까? HTML은 변경할 수 없습니까? 그건 불행한 설정처럼 보입니다. – Ryan

+0

나는 html을 바꿀 수없는 원격 소프트웨어 솔루션을 사용한다. 이 소프트웨어는 전용 CSS 및 js 파일에 코드를 추가하여 사용자 정의 할 수 있습니다. – dotcom27

답변

0

:

body.onlyTheRequiredPages #returning_user_search_box { ... } 

당신은 또한 당신의 요소 스타일 재설정 또 다른 선택 만들 수 있습니다

.specific-page-el { 
    position : absolute 
    right : '0' 
    ... 
} 

을 그리고의 클래스를 수정을 자바 스크립트를 통한 해당 요소

if (window.location.href.indexOf('specific_page.php') != -1) { 
    document.getElementById('returning_user_search_box').className = "specific-page-el" 
} 
0

또는 다음과 같이 입력 할 수 있습니다.

간단한 HTML :

<div id='container'> 
    <span> 
     Hello World 
    </span> 
</div> 

간단한 CSS :

div#container 
{ 
    background-color:#900!important; //Red color here. JS will change it to Blue. 
} 

간단한 JS :

document.getElementById('container').setAttribute("style","background-color:#009!important;"); 

그러나 인라인 스타일이 할 수있는 최악의 일이다.

jsFiddle에 대한 링크.

this과 같이 다른 JS를 사용하십시오.

style=document.getElementById('container').style; 
style.setProperty("background-color","#009","!important;");