jquery - 如何在运行时操作 CSS

标签 jquery css

我有 3 个单选按钮 1) 左 2) 右 3) 无

所以当我将鼠标悬停在单选按钮上时,我会显示以下 3 个 div,每个都有不同的 CSS。

#popupdiv img {
    float: right;
    clear: right;
    margin: 15px
}

#popupdiv img {
    float: left;
    clear: left;
    margin: 15px
}

#popupdiv img {
    float: random; //i want the image to be display randomly in the div
    clear: random;
    margin: 15px
}

<div id='popupdiv'>
    <img src='http://www.hostname.com/images/a.jpg' width='100' height='100' border='0' />
    <img src='http://www.hostname.com/features/b.jpg' width='100' height='100' border='0'/>
    <p>same text for all three divs.....
</div>

我想要做的是拥有一个 div 并根据用户将鼠标悬停在哪个单选按钮上来更改 css。我该怎么做?

最佳答案

您要做的是为每种样式设置不同的类。即:

#popupdiv.left {...}
#popupdiv.right {...}
#popupdiv.random {...}

然后当您将鼠标悬停在单选按钮上时,只需更改您的 div 上的 class() 属性以匹配您想要的任何一个

示例 HTML:

<form id="formid">
<input type="radio" value="left" name="pos_button" id="left_button"> 
<input type="radio" value="right" name="pos_button" id="right_button">
<input type="radio" value="random" name="pos_button" id="random_button">
</form>

Javascript 示例

$('#formid radio').mouseover(function(e){
   document.getElementById('popupdiv').className = $(this).val();
});

我使用 DOM 节点的“className”属性的原因是默认情况下 jQuery 提供 removeClass 和 addClass 方法。但是,我们不知道之前悬停在哪个单选按钮上,实际上,除非您需要,否则没有必要跟踪它。

关于jquery - 如何在运行时操作 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6032456/

相关文章:

jquery - 忽略 Mouseover 元素的子元素中的 Mouseout 事件

css - 单选按钮样式未更改

HTML/CSS : Putting a div with background color over text, 文本仍然可选择

jquery - 如何在 Ajax 请求成功后在我看来增加投票总数

jquery - jQuery只选择一个元素

jquery - 在 Drupal 7 "Zen"主题中使用 jQuery 和 CSS

javascript - 使用 jquery 将两个双引号替换为一个双引号

css - 基金会揭示形式怪异的风格问题

javascript - css 宽度百分比不起作用

html - Angular ng serve,spa 应用程序不加载 css 背景图片