简体   繁体   中英

Change Window Title Depending On Content Editable

I would like it so that a variable (let's say "title")is set to the window title, then, if you set the content to editable, the window will be called "Edit On" and when you turn it off it sets the window title to the variable "title". Although I still don't really understand JavaScript to well so it would be helpful if somebody could write the line of code or help me out. Here is the code that I am currently using.

document.body.contentEditable = document.body.contentEditable == 'true' ? 'false' : 'true'; 
document.designMode=document.designMode == 'on' ? 'off' : 'on';
document.close;

I'm not sure what you're trying to achieve but if you set contentEditable to true for the whole body there's no coming back. How would a user go about leaving 'edit mode'?

What you can do however is adding an empty HTML <div> element to the DOM, make it almost the whole size of the browser window and add something like a 'ready' button.

There are two helpful event listeners for your use case:

onfocus: this will fire as soon as the user clicks somewhere inside the div/typing anything in there. If it gets fired change the document title.

onblur: this will fire as soon as the user clicks somewhere outside the div. If it gets fired reset the document title to it's default.

Additionally you might add a click listener to the ready button to leave edit mode and change the document title as well.

Here's an example:

<html>
<head>
</head>
<body>
<div id="myDiv" style="width:100%;height:90%;background-color:rgb(240,240,240)" contentEditable=true>
</div>
<button id="readyButton">Ready</button>
<script type="text/javascript">
var myDocumentTitle = "My Title";
document.title = myDocumentTitle;
var myDiv = document.getElementById("myDiv");
myDiv.onfocus = function() {
  document.title = "Edit On";
}
myDiv.onblur = function() {
  document.title = myDocumentTitle;
}
var myButton = document.getElementById("myButton");
myButton.onclick = function() {
  document.title = myDocumentTitle;
}
</script>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM