CSS移除Style中单个属性

本文介绍了一种在JavaScript中通过完全替换元素样式属性来间接实现清除特定CSS属性的方法。当需要根据条件更改元素的位置属性(如left、right、top、bottom)时,此方法可以避免属性冲突。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CSS移除Style中单个属性,如color,但是没有找到方法,不管JS还是JQuery,貌似都没有。

我遇到的问题是这样的,有个悬浮的div,页面有一些部分,鼠标移动到上面时,设置悬浮div top/left为鼠标此刻的坐标,但是,如果是比较靠右,或靠下,那就设置right/bottom,如果不清除不需要的,如既有left又有right,就会有问题。

我的处理方法如下。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>移除Style中某个Css属性</title>

    <script language="javascript" src="../script/jquery-1.5.1.js"></script>

    <script type="text/javascript">
        function changeStyle() {
            //不支持
            //document.getElementById("aaa").style.border = null;
            //也不支持
            //document.getElementById("aaa").style.removeProperty('border');

            //Style中有什么Css样式,肯定都知道了,重新写一下,把变的直接拼成新的字符串赋给Style

            var newstyle = "right: 40px; top: 200px;";

            $("#aaa").attr("style", newstyle);
        }
    </script>

    <style type="text/css">
        .mydiv
        {
            position: absolute;
            background-color: #ff0000;
            border: solid 1px #000;
            width: 400px;
            height: 200px;
        }
    </style>
</head>
<body>
    <h3>
        没有找到移除单个Css属性的方法</h3>
    <h3>
        把不变的Css样式写到类中,可能变的写到Style中</h3>
    <div id="aaa" class="mydiv" style="left: 400px; top: 200px;" onclick="changeStyle();">
        点击我改变位置,<br />
        原Style="left: 400px; top: 200px;",<br />
        行Style="right: 40px; top: 200px;";
    </div>
</body>
</html>



说的不是很明白,总结下,就是遇到问题,不要老是往一个方向钻,换个思路,问题解决的也很完美!

转载于:https://my.oschina.net/ind/blog/193741

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值