promises_使用HTML,CSS,jQuery和Promises创建响应式确认弹出窗口

promises

总览 (Overview)

There are many instances I come across where the requirement is for something more than the default JavaScript confirm dialog. While there are many libraries out there that provide this, many of them are over-engineered to do more than the simple requirement of displaying a confirmation dialog with an Ok/Cancel button. Another requirement is how to make the dialog work like the Confirm dialog so that a return value can be tested for the user interaction. This article will show how to build a simple popup dialog using a few lines of jQuery. As part of creating the dialog we will make use of JavaScript promises to handle the click events on the dialog buttons.

我遇到过许多实例,这些实例所需要的不仅仅是默认JavaScript确认对话框。 尽管有许多提供此功能的库,但是它们中的许多都经过了过度设计,以完成除显示带有“确定/取消”按钮的确认对话框的简单要求之外的更多功能。 另一个要求是如何使对话框像“确认”对话框一样工作,以便可以测试用户交互的返回值。 本文将展示如何使用几行jQuery构建一个简单的弹出对话框。 在创建对话框的过程中,我们将使用JavaScript承诺来处理对话框按钮上的click事件。

()

The Template

模板

The first step is to create the template. This involves HTML and CSS only. We want a dialog that is centered (horizontally), is a reasonable distance from the top of the page and is responsive so that it scales to different screen sizes

第一步是创建模板。 这仅涉及HTML和CSS。 我们希望对话框居中(水平),距页面顶部合理距离且具有响应能力,以便缩放到不同的屏幕尺寸

HTML (The HTML)
<div class="popup">
  <p>This is the message</p>
  <div class="text-right">
    <button class="btn btn-cancel">Cancel</button>
    <button class="btn btn-primary">Ok</button>
  </div>
</div> 

That should cover the basics.

那应该涵盖基础知识。

CSS (The CSS)
.popup {
  width: 33.333333%;
  padding: 15px;
  left: 0;
  margin-left: 33.333333%;
  border: 1px solid #ccc;
  border-radius: 10px;
  background: white;
  position: absolute;
  top: 15%;
  box-shadow: 5px 5px 5px #000;
  z-index: 10001;
} 

That should give us something that looks like this

那应该给我们看起来像这样的东西

insert1.jpg
So far so good. We have a dialog that takes up 33.33% of the screen, is centered horizontally and has border, rounded corners and drop shadow.

到目前为止,一切都很好。 我们有一个对话框,占据屏幕的33.33%,位于水平居中位置,并具有边框,圆角和阴影。

You will note the buttons are Bootstrap buttons - for this example I am using Bootstrap to do some of the styling.

您会注意到按钮是Bootstrap按钮-在本示例中,我使用Bootstrap进行某些样式设置。

A modal dialog is not truly modal if you can see and interact with the page that it is overlaying. To complete this we need to create an overlay that will be semi opaque and sit between the Confirmation dialog and the page.

如果可以看到模态对话框,则它不是真正的模态对话框。 为此,我们需要创建一个半透明的覆盖层,该覆盖层位于“确认”对话框和页面之间。

<div class="overlay">
  <div class="popup">
    <p>This is the message</p>
    <div class="text-right">
      <button class="btn btn-cancel">Cancel</button>
      <button class="btn btn-primary">Ok</button>
    </div>
  </div>
</div> 

The CSS for the overlay would look something like this

叠加层CSS看起来像这样

.overlay {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,.85);
  z-index: 10000;
} 

One final CSS change to make. We need some media queries to change the width of the modal at smaller screen sizes.

最后一个CSS更改。 我们需要一些媒体查询来在较小的屏幕尺寸下更改模式的宽度。

Here is an example of how we can do this

这是我们如何做到这一点的一个例子

@media (min-width: 768px) {
  .popup {
    width: 66.66666666%;
    margin-left: 16.666666%;
  }
}
@media (min-width: 992px) {
  .popup {
    width: 50%;
    margin-left: 25%;
  }
}
@media (min-width: 1200px) {
  .popup {
    width: 33.33333%;
    margin-left: 33.33333%;
  }
} 

One final change. Lets add something to make the loading of the dialog a little more impressive. We can take a leaf out of Bootstrap's book and animate the modal into view from the top of the page. To do this we first need to change our popup style to move the dialog above the top of the screen.

最后的改变。 让我们添加一些东西来使对话框的加载更加令人印象深刻。 我们可以从Bootstrap的书中摘取叶子,并在页面顶部为模式添加动画。 为此,我们首先需要更改我们的弹出样式,以将对话框移到屏幕顶部上方。

  top: -100%; 

Now we add a little bit of jQuery to activate the modal on a mouse click

现在,我们添加了一些jQuery以通过单击鼠标来激活模式

<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(function() {
  $(window).click(function() {
    $('.popup').animate({top: '15%'}, 1000);
  });
});
</script> 

That gives us our HTML and CSS. Now for the jQuery.

这为我们提供了HTML和CSS。 现在使用jQuery。

We have two options for creating the markup for the popup

我们有两个选项可以为弹出窗口创建标记

  1. We can simply put it into the document

    我们可以简单地将其放入文档中
  2. We can create the markup dynamically with jQuery

    我们可以使用jQuery动态创建标记

For this example we are going to go with option 2. To achieve this we need to convert the overlay and popup markup into jQuery calls to create the elements required.

对于此示例,我们将使用选项2。要实现此目的,我们需要将overlay和popup标记转换为jQuery调用以创建所需的元素。

We define a function showPrompt() that takes a parameter msg that contain the message we want to display to the user

我们定义一个函数showPrompt() ,该函数带有一个参数msg ,该参数包含要向用户显示的消息

<script>
function showPrompt(msg)
{
  // CREATE THE popup AND APPEND THE msg
  var dialog = $('<div/>', {class: 'popup'})
    .append(
      $('<p/>').html(msg)
    )
    // CREATE THE BUTTONS
    .append(
      $('<div/>', {class: 'text-right'})
        .append($('<button/>', {class: 'btn btn-cancel'}).html('Cancel'))
        .append($('<button/>', {class: 'btn btn-primary'}).html('Ok'))
    );
    
  // CREATE THE overlay AND APPEND THE dialog
  var overlay = $('<div/>', {class: 'overlay'})
    .append(dialog);
  
  // ADD THE overlay AND dialog TO THE PAGE
  $('body').append(overlay);

  // ANIMATE dialog INTO VIEW
  $(dialog).animate({top: '15%'}, 1000);
}
</script> 

That should do it. Lets change the click above to rather show a prompt dynamically. Note we are using the jQuery .one() function because we want to test the buttons and with our current code, the button clicks will keep triggering the animation which we don't want

那应该做。 让我们更改上面的单击以动态显示提示。 请注意,我们正在使用jQuery .one()函数,因为我们要测试按钮,并使用当前代码,单击按钮将不断触发我们不希望的动画

<script src="http://code.jquery.com/jquery.js"></script>
<script>
function showPrompt(msg)
{
  // CREATE THE popup AND APPEND THE msg
  var dialog = $('<div/>', {class: 'popup'})
    .append(
      $('<p/>').html(msg)
    )
    // CREATE THE BUTTONS
    .append(
      $('<div/>', {class: 'text-right'})
        .append($('<button/>', {class: 'btn btn-cancel'}).html('Cancel'))
        .append($('<button/>', {class: 'btn btn-primary'}).html('Ok'))
    );
    
  // CREATE THE overlay
  var overlay = $('<div/>', {class: 'overlay'})
    .append(dialog);
  
  // ADD THE overlay AND dialog TO THE PAGE
  $('body').append(overlay);
  // ANIMATE dialog INTO VIEW
  $(dialog).animate({top: '15%'}, 1000);
}
$(function() {
  $(window).one('click',function() {
    showPrompt('Do you like our confirmation?');
  });
});
</script> 

We are mostly done. There are only two things remaining.

我们大部分完成了。 剩下的只有两件事。

  1. We need to attach click handlers to the buttons

    我们需要将点击处理程序附加到按钮上
  2. We need to capture the user response

    我们需要捕获用户的响应

The click handlers can be added like this

点击处理程序可以像这样添加

    // CREATE THE BUTTONS
    .append(
      $('<div/>', {class: 'text-right'})
        .append($('<button/>', {class: 'btn btn-cancel'}).html('Cancel').on('click', function() {
            $('.overlay').remove();
          }))
        .append($('<button/>', {class: 'btn btn-primary'}).html('Ok').on('click', function() {
            $('.overlay').remove();
          }))
    ); 

Notice that all we are doing on a button click is to remove the .overlay element. Because .popup is a child of .overlay when we remove the latter it removes both.

请注意,我们在单击按钮时所做的只是删除。 叠加元素。 因为.popup.overlay的子级,因此当我们删除后者时,它将同时删除两者。

Almost done - all we need is some way to get the user response. We could pass in a callback function but the use of callbacks is being phased out in favour of Promises so for this example we are going to wrap the creation of our dialog in a Promise and return the promise to our calling code. In our button click we are going to resolve the Promise to either true or false depending on the button clicked.

差不多完成了-我们所需要的只是某种获得用户响应的方法。 我们可以传入一个回调函数,但是为了支持Promises而逐步淘汰了回调的使用,因此在本示例中,我们将在Promise中包装对话框的创建并将承诺返回给调用代码。 在我们单击的按钮中,我们将根据所单击的按钮将Promise解析为true或false。

Here is the showPrompt() function wrapped in a promise

这是包含在promise中的showPrompt()函数

function showPrompt(msg)
{
  // CREATE A Promise TO RETURN
  var p = new Promise(function(resolve, reject) {
  
    var dialog = $('<div/>', {class: 'popup'})
      .append(
        $('<p/>').html(msg)
      )
      .append(
        $('<div/>', {class: 'text-right'})
          .append($('<button/>', {class: 'btn btn-cancel'}).html('Cancel').on('click', function() {
            $('.overlay').remove();
            // RESOLVE Promise TO false
            resolve(false);
          }))
          .append($('<button/>', {class: 'btn btn-primary'}).html('Ok').on('click', function() {
            $('.overlay').remove();
            // RESOLVE Promise TO true
            resolve(true);
          }))
      );
      
    var overlay = $('<div/>', {class: 'overlay'})
      .append(dialog);
    
    $('body').append(overlay);
    $(dialog).animate({top: '15%'}, 1000);
  });
  
  // RETURN THE Promise
  return p;
} 

We just need to modify our jQuery to call this so we can respond to the user click

我们只需要修改jQuery即可调用它,以便我们可以响应用户点击

In the code below we have changed the click to be bound to an <a/> element, and the .one() changed to on() so that we can open the dialog multiple times.

在下面的代码中,我们将click更改为绑定到<a/>元素, .one()更改为on(),以便我们可以多次打开对话框。

$(function() {
  // HANDLE open-dialog CLICK
  $('.open-dialog').on('click',function(e) {
    // PREVENT DEFAULT BEHAVIOUR FOR <a/>
    e.preventDefault();

    // SAVE PROMISE RETURN
    var res = showPrompt('Do you like our confirmation?');
    res.then(function(ret) {
      // SHOW AN ALERT BASED ON WHICH BUTTON WAS CLICKED
      ret ? alert('Ok clicked') : alert('Cancel clicked');
    })
  });
}); 

That's it - we have a confirmation dialog that works on promises.

就是这样-我们有一个对诺言起作用的确认对话框。

Full listing below, working sample here

下面是完整列表, 此处是工作示例

<!doctype html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
.overlay {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,.85);
  z-index: 10000;
}
.popup {
  width: 98%;
  padding: 15px;
  left: 0;
  margin-left: 1%;
  border: 1px solid #ccc;
  border-radius: 10px;
  background: white;
  position: absolute;
  top: -100%;
  box-shadow: 5px 5px 5px #000;
  z-index: 10001;
}
@media (min-width: 768px) {
  .popup {
    width: 66.66666666%;
    margin-left: 16.666666%;
  }
}
@media (min-width: 992px) {
  .popup {
    width: 50%;
    margin-left: 25%;
  }
}
@media (min-width: 1200px) {
  .popup {
    width: 33.33333%;
    margin-left: 33.33333%;
  }
}

</style>
</head>
<body>
<h1>Hello World</h1>
<p><a href="#" class="open-dialog">Open Dialog</a></p>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function showPrompt(msg)
{
  // CREATE A Promise TO RETURN
  var p = new Promise(function(resolve, reject) {
  
    var dialog = $('<div/>', {class: 'popup'})
      .append(
        $('<p/>').html(msg)
      )
      .append(
        $('<div/>', {class: 'text-right'})
          .append($('<button/>', {class: 'btn btn-cancel'}).html('Cancel').on('click', function() {
            $('.overlay').remove();
            // RESOLVE Promise TO false
            resolve(false);
          }))
          .append($('<button/>', {class: 'btn btn-primary'}).html('Ok').on('click', function() {
            $('.overlay').remove();
            // RESOLVE Promise TO true
            resolve(true);
          }))
      );
      
    var overlay = $('<div/>', {class: 'overlay'})
      .append(dialog);
    
    $('body').append(overlay);
    $(dialog).animate({top: '15%'}, 1000);
  });
  
  // RETURN THE Promise
  return p;
}

$(function() {
  // HANDLE open-dialog CLICK
  $('.open-dialog').on('click',function(e) {
    // PREVENT DEFAULT BEHAVIOUR FOR <a/>
    e.preventDefault();

    // SAVE PROMISE RETURN
    var res = showPrompt('Do you like our confirmation?');
    res.then(function(ret) {
      ret ? alert('Ok clicked') : alert('Cancel clicked');
    })
  });
});
</script>
</body>
</html> 

翻译自: https://www.experts-exchange.com/articles/28838/Create-a-responsive-confirmation-popup-using-HTML-CSS-jQuery-and-Promises.html

promises

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值