目前比较全的CSS重设(reset)方法总结

本文介绍了15种CSS重置方法,旨在解决不同浏览器对CSS解释差异的问题,确保跨浏览器的一致性显示效果。

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

  在当今网页设计/开发实践中,使用CSS来为语义化的(X)HTML标记添加样式风格是重要的关键。在设计师们的梦想中都存在着这样的一个完美 世界:所有的浏览器都能够理解和适用多有CSS规则,并且呈现相同的视觉效果(没有兼容性问题)。但是,我们并没有生活在这个完美的世界,现实中发生的失 窃却总是恰恰相反,很多CSS样式在不同的浏览器中有着不同的解释和呈现。

  当今流行的浏览器(如:Firefox、Opera、Internet Explorer、Chrome、Safari等等)中,有一些都是以自己的方式去理解CSS规范,这就会导致有的浏览器对CSS的解释与设计师的CSS 定义初衷相冲突,使得网页的样子在某些浏览器下能正确按照设计师的想法显示,但有些浏览器却并没有按照设计师想要的样子显示出来,这就导致浏览器的兼容性 问题。更糟的是,有的浏览器完全无视CSS的一些声明和属性。

  正因为上述冲突和问题依然存在于这个”不完美的世界”,所以一些设计师想到了一种避免浏览器兼容性问题的方法,那就是CSS Reset,什么是CSS Reset? 我们可以把它叫做CSS重设,也有人叫做CSS复位、默认CSS、CSS重置等。CSS重设就是由于各种浏览器解释CSS样式的初始值有所不同,导致设计师在没有定义某个CSS属性时,不同的浏览器会按照自己的默认值来为没有定义的样式赋值,所以我们要先定义好一些CSS样式,来让所有浏览器都按照同样的规则解释 CSS ,这样就能避免发生这种问题。

  本文总结收集了15套CSS重设实例 ,您可以在前端开发工作中进行参考和使用,有些是很简化的CSS Reset,有些则是非常复杂非常全面的CSS Reset,至于使用哪套,全看您的爱好或需要。

一.最简化的CSS Reset(重设) :

* {
      padding: 0;
      margin: 0;
}

  这是最普遍最简单的CSS重设,将所有元素的padding和margin值都设为0,可以避免一些浏览器在理解这两个属性默认值上的”分歧”。

* {
       padding: 0;
       margin: 0;
       border: 0;
}

  这是在上一个重设的基础上添加了对border属性的重设,初始值为0的确能避免一些问题。

* {
       outline: 0;
       padding: 0;
       margin: 0;
       border: 0;
}

  在前两个的基础上添加了outline属性的重设,防止一些冲突。

 

二.浓缩实用型CSS Reset(重设):

* {
       vertical-align: baseline;
       font-weight: inherit;
       font-family: inherit;
       font-style: inherit;
       font-size: 100%;
       outline: 0;
       padding: 0;
       margin: 0;
       border: 0;
}

  该CSS重设方法出自Perishable Press,这是他常用的方法。

三.Poor Man 的CSS Reset:

html, body {
       padding: 0;
       margin: 0;
}
html {
       font-size:1em;

body {
       font-size:100%;

a img, :link img, :visited img {
       border:0px;

  这个重设方法将html和body下元素的padding和margin都设为0,并分别为html标签和body标签下的所有元素设置了初始的字体大小,最重要的是把有链接的图片的默认边框去掉了。

四.Siolon’s Global Reset

* {
    vertical-align: baseline;
    font-family: inherit;
    fo

nt-style: inherit;
    font-size: 100%;
    border: none;
    padding: 0;
    margin: 0;
}
body {
    padding: 5px;
}
h1, h2, h3, h4, h5, h6, p, pre, blockquote, form, ul, ol, dl {
    margin: 20px 0;
}
li, dd, blockquote {
    margin-left: 40px;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

五.Shaun Inman’s Global Reset

body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, input, p, blockquote, table, th, td, embed, object {
    padding: 0;
    margin: 0;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
    fieldset, img, abbr {
    border: 0;
}
address, caption, cite, code, dfn, em,
h1, h2, h3, h4, h5, h6, strong, th, var {
    font-weight: normal;
    font-style: normal;
}
ul {
    list-style: none;
}
caption, th {
    text-align: left;
}
h1, h2, h3, h4, h5, h6 {
    font-size: 1.0em;
}
q:before, q:after {
    content: ”;
}
a, ins {
    text-decoration: none;
}

六.Yahoo(YUI) CSS Reset:

body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre, 
form,fieldset,input,textarea,p,blockquote,th,td { 
    padding: 0; 
    margin: 0; 

table { 
    border-collapse: collapse; 
    border-spacing: 0; 

fieldset,img { 
    border: 0; 

address,caption,cite,code,dfn,em,strong,th,var { 
    font-weight: normal; 
    font-style: normal; 

ol,ul { 
    list-style: none; 

caption,th { 
    text-align: left; 

h1,h2,h3,h4,h5,h6 { 
    font-weight: normal; 
    font-size: 100%; 

q:before,q:after { 
    content:”; 

abbr,acronym {
    border: 0; 
}

七.Eric Meyer’s CSS Reset

html, body, div, span, applet, object, iframe, table, caption, 
tbody, tfoot, thead, tr, th, td, del, dfn, em, font, img, ins, 
kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, 
h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, 
acronym, address, big, cite, code, dl, dt, dd, ol, ul, li, 
fieldset, form, label, legend { 
    vertical-align: baseline; 
    font-family: inherit; 
    font-weight: inherit; 
    font-style: inherit; 
    font-size: 100%; 
    outline: 0; 
    padding: 0; 
    margin: 0; 
    border: 0; 

:focus { 
    outline: 0; 

body { 
    background: white; 
    line-height: 1; 
    color: black; 

ol, ul { 
    list-style: none; 

table { 
    border-collapse: separate; 
    border-spacing: 0; 

caption, th, td { 
    font-weight: normal; 
    text-align: left; 

blockquote:before, blockquote:after, q:before, q:after { 
    content: “”; 

blockquote, q { 
    quotes: “” “”; 
}

八.Condensed Meyer Reset:

body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6,
pre, form, fieldset, input, textarea, p, blockquote, th, td {
    padding: 0;
    margin: 0;
}
    fieldset, img {
    border: 0;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
ol, ul {
    list-style: none;
}
address, caption, cite, code, dfn, em, strong, th, var {
    font-weight: normal;
    font-style: normal;
}
caption, th {
    text-align: left;
}
h1, h2, h3, h4, h5, h6 {
    font-weight: normal;
    font-size: 100%;
}
q:before, q:after {
    content: ”;
}
abbr, acronym {
    border: 0;
}

九.Ateneu Popular CSS Reset

html, body, div, span, applet, object, iframe, h1, h2, h3, 
h4, h5, h6, p, blockquote, pre, a, abbr, acronym, 
address, big, cite, code, del, dfn, em, font, img, ins, 
kbd, q, s, samp, small, strike, strong, sub, sup, tt, 
var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, 
table, caption, tbody, tfoot, thead, tr, th, td { 
    margin: 0; 
    padding: 0; 
    border: 0; 
    outline: 0; 
    font-weight: inherit; 
    font-style: inherit; 
    font-size: 100%; 
    font-family: inherit; 
    vertical-align: baseline; 

:focus {
    outline: 0;

a, a:link, a:visited, a:hover, a:active{
    text-decoration:none

table {
    border-collapse: separate;
    border-spacing: 0;

th, td {
    text-align: left;
    font-weight: normal;

img, iframe {
    border: none;
    text-decoration:none;

ol, ul {
    list-style: none;

input, textarea, select, button {
    font-size: 100%;
    font-family: inherit;

select {
    margin: inherit;

hr {
    margin: 0;
    padding: 0;
    border: 0;
    color: #000;
    background-color: #000;
    height: 1px
}

十.Chris Poteet’s Reset CSS

* { 
    vertical-align: baseline; 
    font-family: inherit; 
    font-style: inherit; 
    font-size: 100%; 
    border: none; 
    padding: 0; 
    margin: 0; 

body { 
    padding: 5px; 

h1, h2, h3, h4, h5, h6, p, pre, blockquote, form, ul, ol, dl { 
    margin: 20px 0; 

li, dd, blockquote { 
    margin-left: 40px; 

table { 
    border-collapse: collapse; 
    border-spacing: 0; 
}

十一.Tantek Celik Reset CSS

:link,:visited { text-decoration:none } 
ul,ol { list-style:none } 
h1,h2,h3,h4,h5,h6,pre,code { font-size:1em; } 
ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,body,html,p,blockquote,fieldset,input 
{ margin:0; padding:0 } 
a img,:link img,:visited img { border:none } 
address { font-style:normal }

十二.Christian Montoya Reset CSS

html, body, form, fieldset { 
    margin: 0; 
    padding: 0; 
    font: 100%/120% Verdana, Arial, Helvetica, sans-serif; 

h1, h2, h3, h4, h5, h6, p, pre, 
blockquote, ul, ol, dl, address { 
    margin: 1em 0; 
    padding: 0; 

li, dd, blockquote { 
    margin-left: 1em; 

form label { 
    cursor: pointer; 

fieldset { 
    border: none; 

input, select, textarea { 
    font-size: 100%; 
    font-family: inherit; 
}

十三.Rudeworks Reset CSS

* { 
    margin: 0; 
    padding: 0; 
    border: none; 

html { 
    font: 62.5% “Lucida Grande”, Lucida, Verdana, sans-serif; 
    text-shadow: #000 0px 0px 0px; 

ul { 
    list-style: none; 
    list-style-type: none; 

h1, h2, h3, h4, h5, h6, p, pre, 
blockquote, ul, ol, dl, address { 
    font-weight: normal; 
    margin: 0 0 1em 0; 

cite, em, dfn { 
    font-style: italic; 

sup { 
    position: relative; 
    bottom: 0.3em; 
    vertical-align: baseline; 

sub { 
    position: relative; 
    bottom: -0.2em; 
    vertical-align: baseline; 

li, dd, blockquote { 
    margin-left: 1em; 

code, kbd, samp, pre, tt, var, input[type='text'], textarea { 
    font-size: 100%; 
    font-family: monaco, “Lucida Console”, courier, mono-space; 

del { 
    text-decoration: line-through; 

ins, dfn { 
    border-bottom: 1px solid #ccc; 

small, sup, sub { 
    font-size: 85%; 

abbr, acronym { 
    text-transform: uppercase; 
    font-size: 85%; 
    letter-spacing: .1em; 
    border-bottom-style: dotted; 
    border-bottom-width: 1px; 

a abbr, a acronym { 
    border: none; 

sup { 
    vertical-align: super; 

sub { 
    vertical-align: sub; 

h1 { 
    font-size: 2em; 

h2 { 
    font-size: 1.8em; 

h3 { 
    font-size: 1.6em; 

h4 { 
    font-size: 1.4em; 

h5 { 
    font-size: 1.2em; 

h6 { 
    font-size: 1em; 

a, a:link, a:visited, a:hover, a:active { 
    outline: 0; 
    text-decoration: none; 

a img { 
    border: none; 
    text-decoration: none; 

img { 
    border: none; 
    text-decoration: none; 

label, button { 
    cursor: pointer; 

input:focus, select:focus, textarea:focus { 
    background-color: #FFF; 

fieldset { 
    border: none; 

.clear { 
    clear: both; 

.float-left { 
    float: left; 

.float-right { 
    float: right; 

body { 
    text-align: center; 

#wrapper { 
    margin: 0 auto; 
    text-align: left; 
}

十四. Anieto2K Reset CSS

html, body, div, span, applet, object, iframe, 
h1, h2, h3, h4, h5, h6, p, 
blockquote, pre, a, abbr, acronym, address, big, 
cite, code, del, dfn, em, font, img, 
ins, kbd, q, s, samp, small, strike, 
strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, 
fieldset, form, label, legend, 
table, caption, tbody, tfoot, thead, tr, th, td, 
center, u, b, i { 
    margin: 0; 
    padding: 0; 
    border: 0; 
    outline: 0; 
    font-weight: normal; 
    font-style: normal; 
    font-size: 100%; 
    font-family: inherit; 
    vertical-align: baseline 

body { 
    line-height: 1 

:focus { 
    outline: 0 

ol, ul { 
    list-style: none 

table { 
    border-collapse: collapse; 
    border-spacing: 0 

blockquote:before, blockquote:after, q:before, q:after { 
    content: “” 

blockquote, q { 
    quotes: “” “” 

input, textarea { 
    margin: 0; 
    padding: 0 

hr { 
    margin: 0; 
    padding: 0; 
    border: 0; 
    color: #000; 
    background-color: #000; 
    height: 1px 
}

十五.CSSLab CSS Reset

html, body, div, span, applet, object, iframe, h1, h2, h3, 
h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, 
big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, 
small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, 
fieldset, form, label, legend, table, caption, tbody, tfoot, 
thead, tr, th, td { 
    margin: 0; 
    padding: 0; 
    border: 0; 
    outline: 0; 
    font-weight: inherit; 
    font-style: inherit; 
    font-size: 100%; 
    font-family: inherit; 
    vertical-align: baseline; 

:focus { 
    outline: 0; 

table { 
    border-collapse: separate; 
    border-spacing: 0; 

caption, th, td { 
    text-align: left; 
    font-weight: normal; 

a img, iframe { 
    border: none; 

ol, ul { 
    list-style: none; 

input, textarea, select, button { 
    font-size: 100%; 
    font-family: inherit; 

select { 
    margin: inherit; 

/* Fixes incorrect placement of numbers in ol’s in IE6/7 */ 
ol { margin-left:2em; } 
/* == clearfix == */ 
.clearfix:after { 
    content: “.”; 
    display: block; 
    height: 0; 
    clear: both; 
    visibility: hidden; 

.clearfix {display: inline-block;} 
* html .clearfix {height: 1%;} 
.clearfix {display: block;}

  好了,CSS重 设目前先总结到这里,这15套重设方法其实都是有共同点的,也许有的实现方法不同,但大部分都是同一个目的,就是为了让更多的浏览器能显示同样的效果。有 了这些CSS重设作为资料和参考,也许会对你的工作有所帮助甚至提高效率,但是,毕竟这些重设都是别人写的,你完全也可以为自己量身定制一套CSS重设。 如果您有什么意见或是看法,欢迎发表评论。

 

博文来源:http://blog.bingo929.com/css-reset-collection.html

@{ Layout = null; } <!DOCTYPE html> <html> <head> <link href="~/Scripts/layui/css/layui.css" rel="stylesheet" /> <script src="~/Scripts/layui/layui.js"></script> <script src="~/Scripts/jquery-3.4.1.js"></script> <style> body { padding: 10px 20px 20px 20px; width: 97% } .but { margin-top: -5px } .editInfo { display: none; } </style> </head> <body> <fieldset class="layui-elem-field"> <legend> <span class="layui-breadcrumb"> <a href="">基本信息管理</a> <a href="/UserManagem/Index" >员工管理</a> </span> </legend> <div class="layui-field-box"> <div class="layui-form-item"> <div class="layui-inline"> <label class="layui-form-label" style="width: 60px;">员工账号</label> <div class="layui-input-block"> <input type="text" name="code" id="code" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-inline"> <label class="layui-form-label" style="width: 60px;">员工姓名</label> <div class="layui-input-inline"> <input type="text" name="name" id="name" autocomplete="off" class="layui-input"> </div> </div> <button type="button" class="layui-btn layui-btn-radius but" id="searchButton" onclick="Search()"><i class="layui-icon layui-icon-search"></i>查询</button> <button type="button" class="layui-btn layui-bg-blue but" onclick="Add()"><i class="layui-icon layui-icon-addition"></i>添加</button> <button type="button" class="layui-btn layui-btn-danger layui-btn-radius"><i class="layui-icon layui-icon-delete"></i>批量删除</button> <button type="button" class="layui-btn layui-btn-danger layui-btn-radius"><i class="layui-icon layui-icon-export"></i>导出</button> <button type="button" class="layui-btn but" id="searchButton"><i class="layui-icon layui-icon-upload"></i>导入文件</button> </div> </div> </fieldset> <fieldset class="layui-elem-field"> <table class="layui-hide" id="test" lay-filter="test"></table> <script type="text/html" id="toolDemo"> <div class="layui-clear-space"> <a class="layui-btn layui-btn-xs" lay-event="edit" id="Edit"><i class="layui-icon layui-icon-edit"></i>编辑</a> <a class="layui-btn layui-btn-xs layui-bg-orange" lay-event="del"><i class="layui-icon layui-icon-clear"></i>删除</a> </div> <!-- 在视图中添加以下隐藏表单 --> <div class="editInfo" style="padding:15px;"> <form class="layui-form" id="editForm"> <input type="hidden" name="ID" id="ID"> <div class="layui-form-item"> <label class="layui-form-label">员工账号</label> <div class="layui-input-block"> <input type="text" name="UserCode" required lay-verify="required" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">员工姓名</label> <div class="layui-input-block"> <input type="text" name="UserName" required lay-verify="required" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">性别</label> <div class="layui-input-block"> <input type="radio" name="Sex" id="man" value="true" title="男" checked> <input type="radio" name="Sex" value="false" title="女"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">出生日期</label> <div class="layui-input-block"> <input type="text" name="BirthDay" id="BirthDay" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">邮箱</label> <div class="layui-input-block"> <input type="text" name="Email" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">电话</label> <div class="layui-input-block"> <input type="text" name="Tel" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">创建时间</label> <div class="layui-input-block"> <input type="text" name="CreateDate" id="CreateDate" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">地址</label> <div class="layui-input-block"> <input type="text" name="Address" class="layui-input"> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="saveBtn">保存</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form> </div> </script> </fieldset> <script> var tableIns; var form; var isEdit; layui.use(['table', 'form','laydate'], function () { var table = layui.table; form = layui.form; // 修正:移除重复的var声明 var laydate = layui.laydate; // 创建渲染实例 tableIns = table.render({ elem: '#test', url: '/UserManagem/GetList', page: true, cols: [[ { type: 'checkbox', width: '5%', title: '' }, { type: 'numbers', width: '5%', title: '序号' }, { field: 'UserCode', width: '8%', title: '员工账号' }, { field: 'UserName', width: '8%', title: '员工姓名' }, { field: 'Sex', width: '8%', title: '性别', templet: function (d) { if (d.Sex == true) { return "男" } else { return "女"; } } }, { field: 'BirthDay', width: '8%', title: '出生日期', templet: function (d) { return convertJsonDate(d.BirthDay); } }, { field: 'BirthDay', width: '8%', title: '年龄', templet: function (d) { return calculateAge(d.BirthDay); } }, { field: 'Status', width: '8%', title: '是否离职', templet: function (d) { if (d.Status == true) { return "离职"; } else { return "在职"; } } }, { field: 'Email', width: '8%', title: '邮箱' }, { field: 'Tel', width: '8%', title: '电话' }, { field: 'CreateDate', width: '8%', title: '创建时间', templet: function (d) { return convertJsonDate(d.CreateDate); } }, { field: 'Address', width: '8%', title: '员工住址' }, { title: '操作', width: '10.5%', templet: '#toolDemo' } ]], done: function (res, curr, count) { // 数据渲染完成后的回调 if (res.code !== 0) { // 假设0是成功状态码 layer.msg('数据加载失败: ' + res.msg, { icon: 5 }); } }, error: function () { // 请求错误的回调 layer.msg('网络请求错误,请检查接口', { icon: 5 }); } }); //编辑,删除 table.on('tool(test)', function (obj) { // 双击 toolDouble var data = obj.data; // 获得当前行数据 var field = obj.field; // 得到字段 var value = obj.value; // 得到修改后的值 var data = obj.data; // 得到所在行所有键值 // console.log(obj) if (obj.event === 'edit') { layer.open({ type: 1, area: ['500px', '400px'], // 增加高度预留 title: '编辑员工信息', content: $(".editInfo").html(), success: function (layero, index) { // 数据绑定(注意格式转换) laydate.render({ elem: '#BirthDay', // 绑定元素 format: 'yyyy-MM-dd' // 日期格式 }); laydate.render({ elem: '#CreateDate', // 绑定元素 format: 'yyyy-MM-dd' // 日期格式 }); form.val('editForm', { "UserCode": data.UserCode, "UserName": data.UserName, "Sex": data.Sex ? "true" : "false", // 统一转为字符串 "BirthDay": convertJsonDate(data.BirthDay), "Email": data.Email, "Tel": data.Tel, "Address": data.Address }); // 动态渲染表单元素(重要!) form.render(); } }); } else { layer.confirm('真的删除员工 [' + data.UserCode + '] 么', function (index) { obj.del(); // 删除对应行(tr)的DOM结构 layer.close(index); // 向服务端发送删除指令 $.ajax({ url: '/UserManagem/DelInfo', type: 'post', data: { id: data.ID }, success: function (res) { if (res.code == 0) { layer.msg(res.msg, { icon: 6, time: 1500 }, function () { Search(); }) } else { layer.msg(res.msg, { icon: 5, time: 1500 }) } } }) }); } }); }); // 处理日期格式函数 function convertJsonDate(jsonDate) { if (!jsonDate) return ''; try { // 提取时间戳 const timestamp = parseInt(jsonDate.match(/\d+/)[0]); // 创建 Date 对象 const date = new Date(timestamp); // 获取年、月、日 const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); // 返回格式化后的日期 return `${year}-${month}-${day}`; } catch (e) { console.error('日期格式化错误:', e); return jsonDate; } } //表单提交事件,新增和编辑 form.on('submit(demo1)', function (data) { var field = data.field; // 获取表单字段值 $.ajax({ url: '/UserManagem/Add', type: 'post', data: field, success: function (res) { if (res.code == 0) { layer.msg(res.msg, { icon: 6, time: 3000 }, function () { layer.closeAll(); // 关闭所有类型的层 Search(); }); } else { layer.msg(res.msg, { icon: 5, time: 2000 }); } } }) }) //重载,模糊查询 function Search() { var nameVal = $('input[name="name"]').val().trim(); var codeVal = $('input[name="code"]').val().trim(); // 完整重载 - 所有属性属性(options)均可参与到重载中 tableIns.reload({ where: { // 传递数据异步请求时携带的字段 name: nameVal, code: codeVal }, height: 500 // 重设高度 }); } function calculateAge(jsonBirthDate) { if (!jsonBirthDate) return ''; try { // 先转换为日期格式 const birthDate = convertJsonDateToDate(jsonBirthDate); const today = new Date(); let age = today.getFullYear() - birthDate.getFullYear(); const monthDiff = today.getMonth() - birthDate.getMonth(); if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) { age--; } return age; } catch (e) { console.error('年龄计算错误:', e); return ''; } } // 辅助函数:将JSON日期转换为Date对象 function convertJsonDateToDate(jsonDate) { const timestamp = parseInt(jsonDate.match(/\d+/)[0]); return new Date(timestamp); } </script> </body> </html> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WebApplication1.Models; namespace WebApplication1.Controllers { [LoginActionFitter(IsCheck = true)] public class UserManagemController : Controller { // GET: UserManagem AoutEntities1 db = new AoutEntities1(); ReturnListJsonData jsonListData = new ReturnListJsonData(); ReturnJsonData jsonData = new ReturnJsonData(); public ActionResult Index() { return View(); } /// <summary> /// 列表展示 /// </summary> /// <param name="page"></param> /// <param name="limit"></param> /// <param name="name"></param> /// <param name="code"></param> /// <returns></returns> public ActionResult GetList(int page,int limit,string name,string code) { var list = db.Users.ToList(); if (!string.IsNullOrEmpty(name)) { list = list.Where(a => a.UserName.Contains(name)).ToList(); } if (!string.IsNullOrEmpty(code)) { list = list.Where(a => a.UserCode.Contains(code)).ToList(); } var offset = (page - 1) * limit; var resultList = list.Skip(offset).Take(limit); jsonListData.code = 0; jsonListData.count = list.Count; jsonListData.data = resultList; return Json(jsonListData,JsonRequestBehavior.AllowGet); } #region 删除 /// <summary> /// 删除数据 /// </summary> /// <returns></returns> public ActionResult DelInfo(Guid? id) { if (id == Guid.Empty) { jsonData.code = 1; jsonData.msg = "删除失败,未找到当行数据"; } else { //真实删除 var entity1 = db.Users.Find(id); db.Users.Remove(entity1); var result = db.SaveChanges(); if (result > 0) { jsonData.code = 0; jsonData.msg = "删除成功"; } else { jsonData.code = 1; jsonData.msg = "删除失败,请联系管理员"; } } return Json(jsonData, JsonRequestBehavior.AllowGet); } #endregion } 实现添加以及编辑功能
最新发布
07-15
<think>好的,我现在需要帮助用户实现添加和编辑功能。首先,我得仔细看一下用户提供的代码。用户已经完成了前端页面的HTML和JavaScript部分,以及后端的控制器部分,但添加和编辑的功能还没有完实现。 首先看前端部分。用户有一个表格,使用LayUI的表格组件,通过`table.render`加载数据。在工具栏中,有添加按钮(Add函数)和编辑功能(在table.on的tool事件中处理)。表单部分被包含在一个隐藏的div里,当用户点击编辑或添加时,会弹出一个layer窗口显示表单。 添加功能方面,用户点击添加按钮时,会调用Add函数。现在Add函数可能还没有实现,需要创建一个弹窗,显示编辑表单,并且提交数据到后端。编辑功能在点击编辑按钮时,已经能弹出窗口,但保存按钮的事件处理可能没有正确绑定,因为form.on('submit(demo1)')可能没有正确设置表单的提交监听。 后端部分,用户有一个Add动作方法,但可能没有处理POST请求的数据,或者没有正确的逻辑来保存新数据。另外,编辑功能需要更新现有数据,所以需要区分添加和编辑的情况,可能需要传递ID参数来判断是新增还是更新。 接下来,我需要检查前端表单的提交处理。用户当前的代码中有form.on('submit(demo1)'),但表单的lay-filter属性是否正确?在HTML中,编辑表单的id是editForm,但可能没有设置lay-filter为'demo1',所以提交事件可能无法触发。需要确保表单的lay-filter属性与form.on的第二个参数匹配。 另外,在添加时,表单中的ID字段可能不需要,因为添加时ID是空的,而后端应该生成新的Guid。而编辑时需要传递现有的ID。因此,在添加和编辑时,表单中的ID输入框可能需要根据情况处理,比如在添加时不发送ID,或者由后端生成。 后端UserManagemController中,Add方法目前可能只处理添加,但需要同时处理添加和编辑。可能需要检查是否有ID传入,如果有则更新,否则新增。 在前端,当用户提交表单时,应该将数据发送到同一个接口,由后端判断是添加还是编辑。因此,需要确保表单提交的数据包含ID字段,如果ID存在则更新,否则新增。 现在,用户提供的代码中,表单的ID字段是隐藏的,但可能在添加时没有清空,导致错误。所以在Add函数中弹出表单时,应该清空ID字段,并重置表单。 此外,前端的calculateAge函数可能有问题,因为当前的列中BirthDay被重复使用,一次显示出生日期,一次计算年龄,但可能templet引用了相同的字段,导致问题。不过这可能不影响添加编辑功能,暂时忽略。 总结需要完成的步骤: 1. 在前端实现Add函数,弹出表单,并正确初始化表单字段为默认值。 2. 确保表单的提交事件正确绑定到form.on('submit(demo1)'),并发送POST请求到/Add方法。 3. 修改后端Add方法,处理添加和编辑的情况:检查ID是否存在,存在则更新,否则新增。 4. 前端在编辑时正确填充表单数据,包括ID字段,以便后端识别。 5. 处理日期格式的转换,确保提交到后端的日期格式正确。 6. 表单验证,确保必填字段。 7. 成功提交后刷新表格数据。 现在,具体实施: 对于前端添加功能,Add函数应该打开layer窗口,加载编辑表单,并清空所有字段,特别是ID。同时,表单的提交按钮需要触发submit事件,并且lay-filter需要正确设置。 在HTML中,编辑表单的form标签有id="editForm",但lay-filter可能未设置,需要添加lay-filter="editForm",这样在form.on的时候才能监听到。 在JavaScript中,form.on('submit(editForm)')应该用来处理提交事件,而不是'demo1'。用户原来的代码中可能写错了这个参数,导致事件没有正确绑定。 后端的Add方法需要处理POST请求,接收包含ID的字段。如果ID为空或Guid.Empty,则作为新增;否则作为编辑更新。 在前端提交数据时,需要将表单中的数据序列化,并确保日期字段正确转换,比如BirthDay和CreateDate。可能需要使用laydate的值,或者在提交前处理日期格式。 此外,在编辑时,表单中的CreateDate字段可能应该是只读的,或者在提交时不更新,这取决于业务逻辑。但根据用户提供的表单结构,CreateDate是可编辑的,所以可能需要保留。 可能的错误点: - 前端表单的lay-filter名称不正确,导致提交事件未触发。 - 后端Add方法没有正确处理ID,导致无法区分添加和编辑。 - 日期格式转换问题,可能导致模型绑定失败。 - 缺少AntiForgeryToken,可能导致CSRF问题,但用户代码中未涉及,暂时不处理。 现在,修改前端代码: 在Add函数中,弹出layer窗口,并清空ID字段,重置表单。同时,初始化日期控件。 在编辑时,填充表单中的所有字段,包括ID,这样提交时可以带上ID进行更新。 修改表单的form标签,添加lay-filter="editForm"。 在JavaScript中,将form.on('submit(demo1)')改为form.on('submit(editForm)'),以匹配lay-filter的值。 在后端的Add方法中,检查ID参数是否存在。如果ID为空或Guid.Empty,则新建实体;否则查找现有实体并更新字段。 在前端提交表单时,确保所有字段正确序列化,包括ID。可能需要使用form.serialize()方法,或者手动获取每个字段的值。 另外,在提交时,可能需要处理日期字段的格式,确保与后端模型绑定兼容。 最后,在添加或编辑成功后,关闭layer窗口并刷新表格数据。 现在,将这些步骤转化为具体的代码修改。</think>要实现员工管理模块的添加和编辑功能,需从前端和后端两个层面进行完善。以下是完整的实现方案: --- ### ✅ 前端功能实现 #### 1. **添加按钮事件 `Add()`** ```javascript function Add() { layer.open({ type: 1, area: ['500px', '400px'], title: '添加员工信息', content: $(".editInfo").html(), success: function (layero, index) { // 初始化日期控件 laydate.render({ elem: '#BirthDay', format: 'yyyy-MM-dd' }); laydate.render({ elem: '#CreateDate', format: 'yyyy-MM-dd' }); // 清空ID字段,表示添加 $('#ID').val(''); // 重置表单 $('#editForm')[0].reset(); // 动态渲染表单元素 form.render(); } }); } ``` #### 2. **表单提交事件绑定** 确保 `<form>` 标签中添加 `lay-filter="editForm"`,以便监听表单提交: ```html <form class="layui-form" id="editForm" lay-filter="editForm"> ``` 在 JavaScript 中监听表单提交事件: ```javascript form.on('submit(editForm)', function (data) { var field = data.field; // 获取表单字段值 $.ajax({ url: '/UserManagem/Add', type: 'post', data: field, success: function (res) { if (res.code == 0) { layer.msg(res.msg, { icon: 6, time: 1500 }, function () { layer.closeAll(); // 关闭弹窗 Search(); // 刷新表格 }); } else { layer.msg(res.msg, { icon: 5, time: 1500 }); } } }); return false; // 阻止默认提交 }); ``` --- ### ✅ 后端功能实现 #### 1. **完善 `Add` 方法** ```csharp [HttpPost] public ActionResult Add(Users user) { if (user == null) { jsonData.code = 1; jsonData.msg = "数据为空"; return Json(jsonData, JsonRequestBehavior.AllowGet); } if (user.ID == Guid.Empty) { // 添加新员工 user.ID = Guid.NewGuid(); db.Users.Add(user); } else { // 更新已有员工 var existingUser = db.Users.Find(user.ID); if (existingUser == null) { jsonData.code = 1; jsonData.msg = "未找到该员工"; return Json(jsonData, JsonRequestBehavior.AllowGet); } // 更新字段 existingUser.UserCode = user.UserCode; existingUser.UserName = user.UserName; existingUser.Sex = user.Sex; existingUser.BirthDay = user.BirthDay; existingUser.Email = user.Email; existingUser.Tel = user.Tel; existingUser.Address = user.Address; existingUser.CreateDate = user.CreateDate; } try { db.SaveChanges(); jsonData.code = 0; jsonData.msg = user.ID == Guid.Empty ? "添加成功" : "更新成功"; } catch (Exception ex) { jsonData.code = 1; jsonData.msg = "操作失败:" + ex.Message; } return Json(jsonData, JsonRequestBehavior.AllowGet); } ``` --- ### ✅ 功能说明与注意事项 - **添加功能**:弹窗中不携带 ID,后端自动生成 GUID。 - **编辑功能**:弹窗中携带 ID,后端根据 ID 查找并更新记录。 - **表单字段**:确保所有字段(如 `UserCode`, `UserName`, `Sex` 等)都正确绑定并提交。 - **日期格式**:前端使用 `laydate` 控件选择日期,后端需接受 `yyyy-MM-dd` 格式。 - **数据校验**:前端应增加表单验证(如 `required` 属性),后端也应进行空值检查。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值