【问题标题】:ASP.NET - JavaScript onmouseout get original backgroundASP.NET - JavaScript onmouseout 获取原始背景
【发布时间】:2015-04-20 08:34:26
【问题描述】:

我将此代码添加到我的 gridview rowdataBound 中:

 e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E2DED6';this.style.cursor='pointer'")

现在 onmouseout 我想要 CSS 的原始背景,我对 JavaScript 和 jQuery 了解不多,所以如果可能的话,我想将其保留为内联 JavaScript。

我正在寻找这样的东西:

 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='default'")

【问题讨论】:

    标签: javascript c# css asp.net vb.net


    【解决方案1】:

    既然你想保持内联:

    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''")
    

    这应该删除内联样式,并默认为普通样式表。

    你也可以更“大锤”,并删除整个样式属性(虽然这将删除所有设置的内联样式):

    e.Row.Attributes.Add("onmouseout", "this.removeAttribute('style')")
    

    这假设您在元素上设置了默认的 CSS/类。

    更简单的维护方法是使用 css 类:

    e.Row.Attributes.Add("onmouseover", "this.className='myHoverClass'")
    e.Row.Attributes.Add("onmouseout", "this.className=''")
    

    在样式表(或页面)中定义您的类:

    .myHoverClass {
        background-color: #E2DED6;
        cursor: pointer; 
    }
    

    【讨论】:

    • 我用样式表的例子,光标变了,但背景没有,你知道为什么吗?
    • @user2653652 一个原因可能是您通过内联样式设置了背景颜色。这将覆盖任何类。要对其进行测试,您可以这样做:e.Row.Attributes.Add("onmouseover", "this.className='myHoverClass'; this.removeAttribute('style');")(这也将清除任何现有的内联样式)
    • 是的,添加 'this.removeAttribute('style');工作,这是因为我使用标准的 asp.net gridview 模板。我添加到 css background-color: #E2DED6 !重要的是,让它覆盖现有的内联样式,现在它可以像我想要的那样工作,谢谢!
    【解决方案2】:

    使用类似的东西

    <script type="text/javascript">
        var oldgridcolor;
        function SetMouseOver(element) {
            oldgridcolor = element.style.backgroundColor;
            element.style.backgroundColor = '#ffeb95';
            element.style.cursor = 'pointer';
            element.style.textDecoration = 'underline';
        }
        function SetMouseOut(element) {
            element.style.backgroundColor = oldgridcolor;
            element.style.textDecoration = 'none';
    
        }
    </script>
    

    C#

    protected void gvrecords_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if(e.Row.RowType== DataControlRowType.DataRow)
        {
          e.Row.Attributes["onmouseover"] = "javascript:SetMouseOver(this)";
          e.Row.Attributes["onmouseout"] = "javascript:SetMouseOut(this)";
        }
    }
    

    或者你也可以在这里直接添加旧颜色oldgridcolor = "OldColor"

    【讨论】:

      猜你喜欢
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 2017-07-21
      相关资源
      最近更新 更多