자바스크립트를 통해 CSS :hover 효과를 비활성화할 수 있습니까?
브라우저를 사용하지 못하게 하려고 합니다.:hover
자바스크립트를 통한 CSS의 효과.
설정했습니다.a
그리고.a:hover
내 CSS의 스타일, 호버 효과를 원하기 때문에 JS를 사용할 수 없는 경우.그러나 JS를 사용할 수 있다면 CSS 호버 효과를 더 부드러운 효과로 덮어쓰기를 원합니다(예를 들어 jQuery 색상 플러그인 사용).
나는 이것을.
$("ul#mainFilter a").hover(
function(e){ e.preventDefault(); ...do my stuff... },
function(e){ e.preventDefault(); ...do my stuff... });
저도 같이 해봤는데요.return false;
, 하지만 작동하지 않습니다.
다음은 제 문제의 예입니다: http://jsfiddle.net/4rEzz/ .링크는 회색이 되지 않고 옅어져야 합니다.
퍼지가 언급한 것처럼, 해결책은 다음을 사용하여 호버 스타일을 재설정하는 것입니다..css()
그러나 CSS에 지정된 모든 속성을 덮어쓰게 됩니다(여기: http://jsfiddle.net/raPeX/1/ 참조).일반적인 해결책을 찾고 있습니다.
이거 할 줄 아는 사람?
추신: 호버에 대해 설정한 모든 스타일을 덮어쓰고 싶지 않습니다.
순수 자바스크립트 제네릭 솔루션은 없는 것 같습니다.자바스크립트가 CSS를 끌 수 없습니다.:hover
직접 진술합니다.
그러나 다음과 같은 대안을 시도해 볼 수 있습니다.HTML과 CSS를 조금만 뒤져도 상관없다면 자바스크립트를 통해 모든 CSS 속성을 수동으로 재설정할 필요가 없어집니다.
HTML
<body class="nojQuery">
CSS
/* Limit the hover styles in your CSS so that they only apply when the nojQuery
class is present */
body.nojQuery ul#mainFilter a:hover {
/* CSS-only hover styles go here */
}
자바스크립트
// When jQuery kicks in, remove the nojQuery class from the <body> element, thus
// making the CSS hover styles disappear.
$(function(){}
$('body').removeClass('nojQuery');
)
호버만 할당된 두 번째 클래스 사용:
HTML
<a class="myclass myclass_hover" href="#">My anchor</a>
CSS
.myclass {
/* all anchor styles */
}
.myclass_hover:hover {
/* example color */
color:#00A;
}
이제 요소를 클릭한 경우 Jquery를 사용하여 클래스를 제거할 수 있습니다.
제이쿼리
$('.myclass').click( function(e) {
e.preventDefault();
$(this).removeClass('myclass_hover');
});
이 답변이 도움이 되기를 바랍니다.
자바스크립트로 스타일시트와 스타일시트 규칙을 직접 조작할 수 있습니다.
var sheetCount = document.styleSheets.length;
var lastSheet = document.styleSheets[sheetCount-1];
var ruleCount;
if (lastSheet.cssRules) { // Firefox uses 'cssRules'
ruleCount = lastSheet.cssRules.length;
}
else if (lastSheet.rules) { / /IE uses 'rules'
ruleCount = lastSheet.rules.length;
}
var newRule = "a:hover { text-decoration: none !important; color: #000 !important; }";
// insert as the last rule in the last sheet so it
// overrides (not overwrites) previous definitions
lastSheet.insertRule(newRule, ruleCount);
속성을 !중요하게 만들고 이것을 마지막 CSS 정의로 만드는 것은 더 구체적으로 대상화되지 않는 한 이전 정의를 무시해야 합니다.그런 경우에는 규칙을 더 삽입해야 할 수도 있습니다.
이것은 셉틱의 대답과 비슷하지만, 이 방법은 어떻습니까?자바스크립트를 사용하여 비활성화할 CSS 코드를 랩핑합니다.<noscript>
tags. 자바스크립트가 꺼져 있으면 CSS가:hover
가 사용되며, 그렇지 않으면 자바스크립트 효과가 사용됩니다.
예:
<noscript>
<style type="text/css">
ul#mainFilter a:hover {
/* some CSS attributes here */
}
</style>
</noscript>
<script type="text/javascript">
$("ul#mainFilter a").hover(
function(o){ /* ...do your stuff... */ },
function(o){ /* ...do your stuff... */ });
</script>
제가.not()
CSS 연산자와 jQuery'saddClass()
기능.목록 항목을 클릭하면 더 이상 이동하지 않는 예는 다음과 같습니다.
예를 들어,
HTML
<ul class="vegies">
<li>Onion</li>
<li>Potato</li>
<li>Lettuce</li>
<ul>
CSS
.vegies li:not(.no-hover):hover { color: blue; }
jQuery
$('.vegies li').click( function(){
$(this).addClass('no-hover');
});
는 모든 를 을 추천합니다.:hover
성에 대한 입니다.:active
그 장치가 터치를 지원하는 것을 감지할 때.이 기능을 호출할 때 다음과 같이 하십시오.touch()
.
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
CSS를 사용하여 :hover 이벤트가 링크의 모양을 변경하는 것을 방지하고자 합니다.
a{
font:normal 12px/15px arial,verdana,sans-serif;
color:#000;
text-decoration:none;
}
이 간단한 CSS는 링크가 항상 검은색이고 밑줄이 그어지지 않는다는 것을 의미합니다.당신이 통제하고 싶은 것이 외관의 변화뿐인지는 질문으로 알 수 없습니다.
링크 색상만 설정해 보십시오.
$("ul#mainFilter a").css('color','#000');
편집: 또는 Christopher가 제안한 CSS를 사용하는 것이 더 낫습니다.
실제로 이를 해결하기 위한 또 다른 방법은 CSS를 과 함께 덮어쓰는 것입니다.
기존/새로운 스타일시트에 CSS 규칙을 주입할 수 있는 기능을 제공합니다.구체적인 예를 들어보면 다음과 같습니다.
//creates a new `style` element in the document
var sheet = (function(){
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
//add the actual rules to it
sheet.insertRule(
"ul#mainFilter a:hover { color: #0000EE }" , 0
);
4년 전의 나의 독창적인 예를 담은 데모: http://jsfiddle.net/raPeX/21/
이는 순수 자바스크립트로 쉽게 구현할 수 있습니다. 아래 코드를 사용해 보십시오.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
:root {
--orange-color: #fa8e3f;
--dark-organge-color: #bd5305;
--light-color: #fff;
--dark-color: #000;
--grey-color: #f2f2f2;
--transition: all 300ms ease-in-out;
}
.quiz-options {
list-style-type: none;
margin: 1rem 0;
}
.quiz-options li {
color: var(--light-color);
background-color: var(--orange-color);
font-weight: 600;
border: 3px solid var(--orange-color);
border-radius: .5rem;
margin: .7rem 0;
padding: .4rem 1.2rem;
box-shadow: 0 4px 0 0 var(--dark-organge-color);
transition: var(--transition);
}
.quiz-options li.enable-hover-active {
cursor: pointer;
}
.quiz-options li.enable-hover-active:hover {
background-color: var(--grey-color);
color:var(--dark-color);
border-color: var(--grey-color);
box-shadow: 0 4px 0 0 #bbb;
}
.quiz-options li.enable-hover-active:active {
transform: scale(0.97);
}
button {
border: none;
border-radius: 0.5rem;
outline: 0;
font-family: 'Poppins', sans-serif;
font-size: 1.2rem;
font-weight: 600;
padding: .5rem 1rem;
margin: 0 auto;
text-transform: uppercase;
cursor: pointer;
display: block;
background-color: var(--grey-color);
color: var(--dark-color);
letter-spacing: 2px;
transition: var(--transition);
box-shadow: 0 4px 0 0 #bbb;
}
</style>
<body>
<ul class="quiz-options">
<li>option 1</li>
<li>option 2</li>
<li>option 3</li>
<li>option 4</li>
</ul>
<button type="button" id="check-answer" onclick="enableHoverActive()">Enable hover & active</button>
<script>
function enableHoverActive() {
if (document.getElementById('check-answer').textContent == 'Enable hover & active') {
document.getElementById('check-answer').textContent = 'Disable hover & active';
document.querySelectorAll('li').forEach((option) => {
option.classList.add('enable-hover-active');
});
} else {
document.getElementById('check-answer').textContent = 'Enable hover & active';
document.querySelectorAll('li').forEach((option) => {
option.classList.remove('enable-hover-active');
});
}
}
</script>
</body>
</html>
결과는 다음과 같습니다.
"사용 안 함"일 때, 호버링 및 클릭 옵션
"활성화"된 경우, 호버링 및 클릭 옵션
언급URL : https://stackoverflow.com/questions/2754546/can-i-disable-a-css-hover-effect-via-javascript
'programing' 카테고리의 다른 글
LibCOS가 존재합니까? (0) | 2023.10.15 |
---|---|
jQuery 문자열 찾기 및 바꾸기 (0) | 2023.10.15 |
모듈의 자식으로 모듈로 라우팅하는 방법 - Angular 2 RC 5 (0) | 2023.10.15 |
링크하는 동안 전역 변수에 대한 정의되지 않은 참조 (0) | 2023.10.15 |
워드프레스:로그인 페이지에서 "비밀번호 분실" 텍스트를 사용자 정의하려면 어떻게 해야 합니까? (0) | 2023.10.15 |