需要自定义提示框帮助

Javascript Custom prompt box help needed

本文关键字:帮助 提示 自定义      更新时间:2023-09-26

我已经为Javascript做了一个自定义提示框,所以我不必使用股票提示框,但是我不知道如何直接从cPrompt()函数返回值。我希望能够像正常提示一样使用它,并且能够像var name = cPrompt("Whats your name")这样做,但是要关闭自定义提示,我必须使用事件来触发一个称为ok()的功能,当单击按钮时。这阻止了我直接从cPrompt函数返回值。有人知道我该怎么做吗?下面是我的代码:

HTML:

    <html>
<head>
    <title>Custom Prompt</title>
</head>
<body>
    <p>content</p>
    <button onclick="cPrompt('Message goes here')">Click me</button>
    <div id="overlay"></div>
    <div id="pBox">
        <div id="cPromptOut" onclick="ok()"></div>
        <input type="text" id="cPromptIn"/>
    </div>
    <link rel='stylesheet' href='customPrompt.css'/>
    <script src='customPrompt.js'></script>
</body>
</html>
CSS:

#overlay{
    width:100%;
    height:100%;
    position:fixed;
    background-color:grey;
    opacity:0.5;
    z-index: 10;
    display: none;
    left:0;
    top:0;
}
#pBox{
    width:50%;
    height:30%;
    position:fixed;
    background-color:red;
    left:25%;
    top:20%;
    z-index: 11;
    display:none;
}
#cPromptOut{
    width:100%;
    height:50%;
    background-color: green;
    z-index: 12;
    text-align: center;
    font-size: 1.5em
}
#cPromptIn{
    width:100%;
    height:50%;
    border:1px solid black;
    text-align: center;
    font-size: 1.5em
}

JS:

var overlay = document.getElementById("overlay")
var pBox = document.getElementById("pBox")
var cPromptOut = document.getElementById("cPromptOut")
var In = document.getElementById("cPromptIn").value
function cPrompt(msg){
    
    overlay.style.display = "block";
    pBox.style.display = "block";
    cPromptOut.innerHTML = msg;
}
function ok(){
    overlay.style.display = "none";
    pBox.style.display = "none";
}
console.log(cPrompt("enter you name"))

所以现在我不能收集框中的值。有人知道我该怎么做吗?记住,我希望能够像调用提示符一样调用它,而不必使用任何其他调用,如console.log(cPrompt("say something"))。我可能是想多了,或者可能是不可能的,欢迎任何想法

EDIT - ok,所以它不会像console.log(cPrompt('message'))那么简单,但是有一个有点的方法去做你想做的事情。看看这个由托比·何的蹦床改编的小提琴。由于某些原因,我无法在chrome中使用它,但firefox可以做到。最酷的部分是在main()中(它必须在run(main())调用

中)
function main(){
    log('start listening');
    log(yield prompt('hello'));//the code "seems" to halt here.
    log('end script');
}

你又问了一个很难的问题,所以它不会像你想的那么容易,但它在这里。另外,如果你能告诉我们你到目前为止都做了些什么,那就太好了。

BEFORE EDIT:

乍一看,我认为这是不可能的。如果您的cPrompt()函数保存解释器,因此它可以返回用户的输入,我认为页面将冻结。你试过这样的东西吗?

//This will probably freeze the page
function cPrompt(_msg){
    ...//init the prompt
    while( input == null){}//your prompt sets input in an event
    return input;
}

通常的方法是传递一个像这样的闭包

function whenInput(_input){console.log(_input);}
cPrompt('message', whenInput);

现在,我认为在js 1.7中可能有一种新的生成器。

那么,你试过什么?