Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JavaScript and HTML to create a blog reader

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use JavaScript and HTML to create a blog reader". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to create a blog reader using JavaScript and HTML".

Create a new project in Visual Studio

Create a new project called WindowsBlogReader for our application. Here is how to do it:

Start Visual Studio.

On the start Page tab, click New Project. The New Project dialog box opens.

In the installed pane, expand JavaScript and select the Windows App Store Apps template type. The project templates available to JavaScript are displayed in the center pane of the dialog box.

In the center pane, select the split Application project template.

In the name text box, enter WindowsBlogReader.

Click OK to create the project. It will take some time.

The following is the structure of the project displayed in solution Explorer. The pages folder contains two sets of files, one for the item page and the other for splitting the page. Each of these groups is PageControl, a set of HTML, CSS, and JavaScript files that define pages that the application can navigate to or use as custom controls.

The new project contains the HTML, CSS, and JavaScript files needed to create the item PageControl and split the PageControl. We will add a file for the item details PageControl later.

Launch our new Windows App Store app

If you really want to see the appearance of a basic separated application, press F5 to generate, deploy, and start the application. The application is displayed as a full-screen page titled "WindowsBlogReader" with a list of sample items displayed as a grid. Each project represents a set of data. Click or click an item in the list to navigate to the split page. The split page contains two core content areas. On the left, you can see a list of items associated with the selected group. On the right, you can see the contents of the selected project. You can return to the project page by clicking or clicking the back button on the page.

When the application is run, the application extracts (or links in) HTML, CSS, and JavaScript from the items.html and injects them into the default.html page that is the starting page of the application. There are some restrictions on what code running in the application container can do by default. For example, your application cannot access the Internet or the camera unless you declare that the application requires this access and that the user granted this access when the application was installed. For more information, open package.appxmanifest and go to the license scope tab.

Change the title and background color

Let's perform two simple tasks to customize the application.

To change the application title, open items.html and replace the H2 element text in itemspage with "Windows team blog", as shown here.

Windows Team Blogs

To set the background color of the application, open default.css and add this background-color property to # contenthost.

# contenthost {height: 100%; width: 100%; background-color: # 0A2562;}

Press F5 to generate, deploy, and start the application. Notice that the title of the project page has changed and the background color of the project page and split page is blue.

The images folder in the Note project contains default files that the system uses for tiles and splash screens that are applied when the application is started. In this tutorial, we will not change these contents, but you can use other images as you like. Simply add the image file you want to use to the images folder. Open package.appxmanifest and replace the contents of "logo", "small logo" and "splash screen" on the "Application UI" tab with the path to your image file.

Replace sample data

The project template contains sample data that you see when you run the application. We used these steps to replace these sample data with data from the ATOM source for the Windows team blog:

Delete sample data

Open data.js, which contains sample data for the application.

We don't need the generateSampleData function, so you can delete it.

/ / Returns an array of sample data that can be added to the application's / / data list. Function generateSampleData () {/ / Omitted code. }

We don't need this code, so you can delete it:

/ / TODO: Replace the data with your real data. / / You can add data from asynchronous sources whenever it becomes available. GenerateSampleData () .forEach (function (item) {list.push (item);})

Set variables and functions

Add this code to data.js (var list = new WinJS.Binding.List () at the beginning of the file; before the declaration). This code sets the variables we need and the functions that populate them. When performing the steps in this tutorial, you can use the comments it contains to find out where to place the code at each step.

/ / Set up array variables var dataPromises = []; var blogs; / / Create a data binding for our ListView var blogPosts = new WinJS.Binding.List () / Process the blog feeds function getFeeds () {/ / Create an object for each feed in the blogs array / / Get the content for each feed in the blogs array / / Return when all asynchronous operations are complete} function acquireSyndication (url) {/ / Call xhr for the URL to get results asynchronously} function getBlogPosts () {/ / Walk the results to retrieve the blog posts} function getItemsFromXml (articleSyndication, bPosts, feed) {/ / Get the info for each blog post}

Define blog list

To make this example simple, we include a list of hard-coded URL in the blogs array.

Add this code to the getFeeds function. This code adds the JSON array to the blogs array. Each JSON array contains multiple JSON objects to store content from the source. The JSON object is an unsorted container of name / value pairs. For example, the blog title is stored in a JSON object named title, with a value retrieved from the ATOM source. Using the JSON object makes it easy for us to bind content from the source to the control of the application in the future.

/ Create an object for each feed in the blogs array blogs = [{key: "blog1", url: 'http://blogs.windows.com/skydrive/b/skydrive/atom.aspx', title:' tbd', updated: 'tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog2", url:' http://blogs.windows.com/windows/b/windowsexperience/atom.aspx', title: 'tbd' Updated: 'tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog3", url:' http://blogs.windows.com/windows/b/extremewindows/atom.aspx', title: 'tbd', updated:' tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog4", url: 'http://blogs.windows.com/windows/b/business/atom.aspx', title:' tbd' Updated: 'tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog5", url:' http://blogs.windows.com/windows/b/bloggingwindows/atom.aspx', title: 'tbd', updated:' tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog6", url: 'http://blogs.windows.com/windows/b/windowssecurity/atom.aspx', title:' tbd' Updated: 'tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog7", url:' http://blogs.windows.com/windows/b/springboard/atom.aspx', title: 'tbd', updated:' tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog8", url: 'http://blogs.windows.com/windows/b/windowshomeserver/atom.aspx', title:' tbd' Updated: 'tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog9", url:' http://blogs.windows.com/windows_live/b/developer/atom.aspx', title: 'tbd', updated:' tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog10", url: 'http://blogs.windows.com/ie/b/ie/atom.aspx', title:' tbd' Updated: 'tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog11", url:' http://blogs.windows.com/windows_phone/b/wpdev/atom.aspx', title: 'tbd', updated:' tbd', acquireSyndication: acquireSyndication, dataPromise: null}, {key: "blog12", url: 'http://blogs.windows.com/windows_phone/b/wmdev/atom.aspx', Title: 'tbd', updated:' tbd', acquireSyndication: acquireSyndication, dataPromise: null}]

Retrieve source data

For the steps in this section, we use the Windows library for JavaScript to manage federated sources.

Add this code to the acquireSyndication function. We call the Windows.JS.xhr function to retrieve the source content. This call is asynchronous. Fortunately, the program has dealt with many complex problems that may be encountered when making asynchronous calls for us. When the xhr returns, we will receive the promise of the result, which will be returned to the caller.

/ / Call xhr for the URL to get results asynchronously return WinJS.xhr ({url: url, headers: {"If-Modified-Since": "Mon, 27 Mar 1972 00:00:00 GMT"}})

Now, let's add the code to the getFeeds function to call the acquireSyndication function for each blog in the blogs array, and add the promise dataPromises returned to our promise array. We call the WinJS.Promise.join function and wait for all the promises to be met before returning from the getFeeds. This ensures that we have all the information we need before displaying the ListView control.

/ / Get the content for each feed in the blogs array blogs.forEach (function (feed) {feed.dataPromise = feed.acquireSyndication (feed.url); dataPromises.push (feed.dataPromise);}); / / Return when all asynchronous operations are complete return WinJS.Promise.join (dataPromises) .then (function () {return blogs;})

Next, add this code to the getBlogPosts function. For each blog in the blogs array, we analyze the XML source data for the information we need. First, we use the responseXML attribute to get the response body, and then use the querySelector method and the required selector to get the blog title and the last update date. We use Windows.Globalization.DateTimeFormatting.DateTimeFormatter to convert the displayed date of the last update.

If articlesResponse.responseXML is null, an error occurred while loading the blog, so we will display an error message in the location where the blog was published.

/ / Walk the results to retrieve the blog posts getFeeds () .then (function () {/ / Process each blog blogs.forEach (function (feed) {feed.dataPromise.then (function (articlesResponse) {var articleSyndication = articlesResponse.responseXML; if (articleSyndication) {/ / Get the blog title feed.title = articleSyndication.querySelector ("feed > title"). TextContent / / Use the date of the latest post as the last updated date var published = articleSyndication.querySelector ("feed > entry > published"). TextContent; / / Convert the date for display var date = new Date (published); var dateFmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter ("month.abbreviated day year.full") Var blogDate = dateFmt.format (date); feed.updated = "Last updated" + blogDate; / / Get the blog posts getItemsFromXml (articleSyndication, blogPosts, feed);} else {/ / There was an error loading the blog. Feed.title = "Error loading blog"; feed.updated = "Error" BlogPosts.push ({group: feed, key: "Error loading blog", title: feed.url, author: "Unknown", month: "?", day: "?", year: "?" Content: "Unable to load the blog at" + feed.url}) }}); return blogPosts

Finally, add this code to the getItemsFromXml function. First, we use querySelectorAll to get a collection of blog articles and information about each blog post. Then we use querySelector to get information about each blog post. We use Windows.Globalization.DateTimeFormatting.DateTimeFormatter to convert the displayed date of the last update. Finally, we use the push method to store the information for each blog post in the corresponding entry in the bPosts array.

/ / Get the info for each blog post var posts = articleSyndication.querySelectorAll ("entry"); / / Process each blog post for (var postIndex = 0; postIndex

< posts.length; postIndex++) { var post = posts[postIndex]; // Get the title, author, and date published var postTitle = post.querySelector("title").textContent; var postAuthor = post.querySelector("author >

Name "). TextContent; var postPublished = post.querySelector (" published "). TextContent; / / Convert the date for display var postDate = new Date (postPublished); var monthFmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter (" month.abbreviated "); var dayFmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter (" day "); var yearFmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter (" year.full "); var blogPostMonth = monthFmt.format (postDate) Var blogPostDay = dayFmt.format (postDate); var blogPostYear = yearFmt.format (postDate); / / Process the content so it displays nicely var staticContent = toStaticHTML (post.querySelector ("content") .textContent) / Store the post info we care about in the array bPosts.push ({group: feed, key: feed.title, title: postTitle, author: postAuthor, month: blogPostMonth.toUpperCase (), day: blogPostDay, year: blogPostYear, content: staticContent});}

Make data available

Now that we have completed the code to store the source data in an array, we need to group the source data as expected by the ListView control. We also need to complete the task of binding the source data to the ListView control.

The getItemsFromGroup function calls the createFiltered method and returns the blog post for the specified blog. The getItemsFromGroup function depends on the variable list.

Var list = new WinJS.Binding.List ()

Replace this definition with a call to the getBlogPosts function, which returns the blogPosts variable. This is a WinJS.Binding.List object.

Var list = getBlogPosts ()

Note that calling the createGrouped method sorts blog posts by the specified key (in this case, the blog to which each post belongs).

Var groupedItems = list.createGrouped (function groupKeySelector (item) {return item.group.key;}; function groupDataSelector (item) {return item.group;})

Update item PageControl

The main function of the item PageControl is the ListView control implemented using WinJS.UI.ListView. Each blog has an item in this list. Let's modify the ListView entry provided in the template to include the blog title and the date the blog was last updated.

Open items.html. We need to update the HTML in this div tag to reflect the content in our blogs array.

Make the following updates:

Because not every blog has an image, remove the img tag.

In the H7 tag, update textContent: subtitle to textContent: updated. This places the last update date in the overlay section of the ListView project.

Move the h5 tag that precedes the div of class item-overlay. This places the blog title in the main part of the ListView project.

The results are shown below.

To set the color of the list item to light blue, open items.css and add the background-color property shown here. In addition, change the size of the second line from 90px to 60px in the-ms-grid-rows attribute, as shown here, because we only show the date of the last update in the override.

.itemspage .itemslist .item {- ms-grid-columns: 1Frr;-ms-grid-rows: 1fr 60px; display:-ms-grid; height: 250px; width: 250px; background-color: # 557EB9;}

To set the font size and margins for the blog title, add this code to items.css.

.itemspage .itemslist. Win-item. Item-title {- ms-grid-row: 1; overflow: hidden; width: 220px; font-size: 24px; margin-top: 12px; margin-left: 15px;}

Update split PageControl

Open split.html. The HTML for the split pages in the template uses the same name as the sample data. We need to update the HTML in this div tag to reflect the name in our blogPosts array.

Make the following updates:

Replace the img tag with the new... Node.

In the H7 tag, change textContent: subtitle to textContent: author.

Delete h5 tag

The results are shown below.

| |

Note that we use pipe characters as delimiters because HTML does not contain tags for drawing vertical lines.

Because we don't have all the information included in the sample data, removing this code from articleSection simplifies the page.

To set the color of the text block and the project date, font, and margin of the text, open split.css and add this code.

.splitpage .itemlistsection .itemlist .item. Item-date {- ms-grid-column: 1; background-color: # 557EB9;} .splitpage .itemlistsection .itemlist .item. Item-date. Item-month {margin-top: 12px; margin-left: 12px; margin-bottom: 4px; font-weight: bold; font-size: 28px } .splitpage .itemlistsection .itemlist .item. Item-date. Item-day {margin-left: 12px; font-size: 28px;}

To get the page layout we need, change this-ms-grid-row property from "1" to "2". This causes the page title to fill the entire first line and put the ListView and the article on the second line.

.splitpage .articlesection {- ms-grid-column: 2;-ms-grid-row: 2;-ms-grid-row-span: 2; margin-left: 50px; overflow-y: auto; padding-right: 120px; position: relative; z-index: 0;}

Now, try running the app again. Press F5 to build, deploy, and start this application. The page title can be seen immediately, but there is a short delay in the application of retrieving the source data. After meeting all the promises, you can see one item for each blog in ListView. (this code adds these items to the ListView in the order in which they meet the promise. Clicking or clicking an item in ListView will take you to a split page that contains a list of blog posts for the selected blog as well as the contents of the selected blog posts. The first blog post is selected by default.

Click the back arrow to return to the item page. Notice that the tiles returned to the screen have a transition animation. This is a feature in the Windows JavaScript library that enables controls and other user interface elements to move according to the UX guidelines for Windows App Store apps.

Add item details PageControl

Item details PageControl displays the title of the blog post as its own, and has an area that contains the content of the blog post.

To add item details PageControl:

In solution Explorer, right-click the pages folder and select add > New folder.

Name the folder itemDetail.

In solution Explorer, right-click the itemDetail folder and select add > New item.

Select "JavaScript" > "Windows App Store" > "Page Control" and use the file name itemDetail.html.

Click add to create itemDetail.css, itemDetail.html, and itemDetail.js files in the pages/itemDetail folder.

Open itemDetail.html and update the main section shown here. This code defines the page layout. (this is a simplified version of the itemDetail.html page code included in the grid application template. )

ItemDetail Welcome to itemDetail

Content goes here.

Replace the Main content section with the following code.

Open itemDetail.js and update the code for the ready function shown here. This code displays the title and content when the user navigates to this page. (this is a simplified version of the itemDetail.js page code included in the grid application template. )

Ready: function (element, options) {/ / Display the appbar but hide the Full View button var appbar = document.getElementById ('appbar'); var appbarCtrl = appbar.winControl; appbarCtrl.hideCommands (["view"], false); var item = options & & options.item? Options.item: Data.items.getAt (0); element.querySelector (".titlearea .pagetitle"). TextContent = item.title; element.querySelector ("article. Item-content") [xss_clean] = item.content;}

Now, let's define the style for the item details page. Open itemDetail.css and replace the template code with the code shown here.

.itemDetail section [role=main] {- ms-grid-row: 2; display: block; height: 100%; overflow-x: auto; position: relative; width: 100%; z-index: 0;} .itemDetail section [role=main] article {/ * Define a multi-column, horizontally scrolling article by default. * / column-fill: auto; column-gap: 80px; column-width: 480px; height: calc (100%-50px); margin-left: 120px; width: 480px;} .itemDetail section [role=main] article. Item-content p {margin-bottom: 20px; margin-right: 20px; vertical-align: baseline } @ media screen and (- ms-view-state: snapped) {.itemDetail section [role=main] article {/ * Define a single column, vertically scrolling article in snapped mode. * /-ms-grid-columns: 300px 1Frr;-ms-grid-row: 2;-ms-grid-rows: auto 60px; display:-ms-grid; height: 100%; margin-left: 20px; overflow-x: hidden; overflow-y: auto; width: 300px } .itemDetail section [role=main] article. Item-content {padding-bottom: 60px;}} @ media screen and (- ms-view-state: fullscreen-portrait) {.itemDetail section [role=main] article {margin-left: 100px;}}

Add an application bar with a command to display the project details page

We add an application bar that contains buttons that can be used to navigate to the project details page and make this button appear only when we are on the split page.

Open default.html and uncomment this code.

Modify the definition of the placeholder button to create a button labeled full View on the far right side of the application bar, as shown here.

When navigating to the project page and the project details page, we do not want the full View button to be displayed on the application bar. Add this code to the ready function in items.js to hide the button. (this code already appears in the itemDetail.js function in the ready we created. )

/ / Display the appbar but hide the Full View button var appbar = document.getElementById ('appbar'); var appbarCtrl = appbar.winControl; appbarCtrl.hideCommands (["view"], false)

When we navigate to the split page, the full View button will be displayed on the application bar. Add this code to the ready function in split.js to display the button.

/ / Display the appbar and show the Full View button var appbar = document.getElementById ('appbar'); var appbarCtrl = appbar.winControl; appbarCtrl.showCommands (["view"], false)

Navigate from split PageControl to item details PageControl

When the user clicks the full View button on the application bar, the application navigates to the item details PageControl and displays the title and content of the selected blog post.

Open split.js. Add this variable declaration after the utils variable declaration.

/ / The selected item var post

Add this statement to the ready function before the second call to querySelector so that you can set the this.items first. This code sets the post variable to the index of the first blog post when the user navigates to the page.

/ / Get the first item, which is the default selection post = this._items.getAt (0)

Add this statement to the _ selectionChanged function, which is after the statement that sets the this._itemSelectionIndex. This code sets the post variable to the index of the blog post selected by the user.

/ / Get the item selected by the user post = this._items.getAt (this._itemSelectionIndex)

In addition to the _ selectionChanged function, add this event handler function after the post variable declaration. This handler is called when the user clicks the full View button. The WinJS.Navigation.navigate function loads the item details page and passes the selected blog post as an item.

Function displayFullView () {/ / Display the selected item in the item detail page nav.navigate ('/ pages/itemDetail/itemDetail.html', {item: post});}

Add this code to the ready function (after the code we added) to display the full View button. This code registers our displayFullView function as the event handler for the click event of the full View button.

/ / Register the event handler for the FullView button document.getElementById ('view') .addEventListener ("click", displayFullView, false)

Press F5 to run the application. Clicking the project on the project page will take you to the split page, which contains a list of blog posts and the contents of the selected blog posts. Click or click the blog post, and the content of the article is displayed in the right column. To display the application bar, right-click or swipe from the bottom or top (if your system supports touch).

Click or click the "full View" button, and our application will display the contents of the selected blog post on the project details page.

If you click or click the back button, return to the split page. The first item in ListView is selected, it is not necessarily the item you choose to display on the project details page. You can add code as needed to save and restore the selected items.

The template code used in our application can display both horizontal and vertical directions. Rotate your computer, or run your application in the Microsoft Visual Studio Express 2012 for Windows 8 simulator, and then rotate the monitor. The item page looks like this.

The appearance of the split page is as follows. Note that only the ListView control is displayed before selecting the project. The blog posts are then displayed vertically. If you click the Full View button, the blog post is displayed horizontally.

Thank you for your reading, the above is the content of "how to use JavaScript and HTML to create a blog reader". After the study of this article, I believe you have a deeper understanding of how to use JavaScript and HTML to create a blog reader, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report