本文是使用了Electron.js 构建一个 Pc端 的 “每日一文”
不把UI都复刻过来,只是把功能相应地实现一下。
DEMO介绍
-
应用跟手机端的“每日一文”差不多,其实这APP也是用了它的API接口
-
实现了的功能:
2.1 打开程序自动获取一篇文章,以及获取到其作者信息(信息来源于百度百科)
2.2 可以保存喜欢的文章到本地(/saveArticles)
2.3 可以手动获取随机一篇文章 -
未完成 :
长按保存按钮进行文章另存为的操作
效果图
文章一览.png 作者.png 功能按钮.png实现
用到的轮子有:
- Button.css - 一个高度可定制的、免费并且开源的按钮 CSS 样式库
Button.css.png
因为就一个单页面应用,我也就不把style另外拎出来了(虽然不利于后期重构和维护),但对于一个一两百行的小DEMO而言,我就懒一点了。
为了能看清楚代码结构,我就把index.html部分抽出来贴吧:
index.html - <head>部分
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>遇文</title>
<script>window.$ = window.jQuery = require('jquery');</script>
<link rel="stylesheet" href="css/buttons.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<style>
...
</style>
</head>
index.html -style 样式
<style>
@font-face {
font-family: NotoSansHans-Light; /*这里是说明调用来的字体名字*/
src: url('./assets/NotoSansHans-Light.otf'); /*这里是字体文件路径*/
}
@font-face{
font-family:NotoSansHans-Regular;
src:url('./assets/NotoSansHans-Regular.otf');
}
@font-face{
font-family: Title;
src:url('./assets/Title.ttf');
}
/*是否控制开启透明*/
body{
-webkit-app-region: drag;
}
button,.button{
-webkit-app-region: no-drag;
}
body,#DailyArticle{
margin:0;
}
/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
::-webkit-scrollbar
{
width: 10px;
background-color: #F5F5F5;
}
/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track
{
border-radius: 10px;
background-color: #f9f9f9;
}
/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb
{
border-radius: 4px;
-webkit-box-shadow: 0 0 7px rgba(0, 0, 0, 0.24);
background-color: rgb(79, 181, 255);
}
.DailyArticle{
background: #F1F2F1;
background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
font-family: 'NotoSansHans-Light';
padding: 1em;
font-size: 1.2em;
line-height: 2.4em;
text-indent: 2em;
color: #424242;
text-shadow: 1px 1px 14px rgba(189, 189, 189, 0.48);
border: 1px solid #d4d4d4;
border-radius: 6px;
box-shadow: 1px 1px 20px rgb(220, 220, 220);
margin: 1em;
transition: .3s all ease-in-out;
}
.DailyArticle:hover{
box-shadow: 1px 1px 20px rgb(185, 185, 185);
}
.DailyArticle hr{
color:#afafaf;
border-style: dashed;
margin-top: -18px;
}
.articleTitle{
font-family: 'Title';
font-family: 'Title';
font-size: 3em;
margin: 1em 0;
}
.articleContent{
font-family: 'NotoSansHans-Regular';
}
.articleFooter{
text-align:right;
}
::selection{
background: #d6d6d6;
}
/*文章后的点赞、收藏、保存 按钮*/
.handleArticle{
margin: 5em auto;
text-align: center;
}
.handleArticle button{
width: 100px;
height: 100px;
font-size:2em;
margin-right: 30px;
transition:.3s all;
}
.handleArticle button:hover{
margin-right: 50px;
}
.authorAvatar-img{
max-width: 200px;
border: 8px solid #fff;
border-radius: 2px;
box-shadow: 0px 5px 20px #b3b3b3;
margin: 15px auto;
display: block;
}
#text_saved{
background-color: #dedede;
font-size: 0.6em;
border-radius: 5px;
margin-top: 4em;
}
.refresh{
text-align:right;
}
.authorName{
font-size: 3em;
line-height: normal;
}
</style>
index.html - 页面脉络结构
<html>
<head>...</head>
<body>
<!-- <h1>随机一文</h1> -->
<div id="DailyArticle" class="DailyArticle">
<div class="articleTitle"></div>
<hr>
<div class="articleContent">正在获取中...</div>
<div class="articleFooter"></div>
<div class="handleArticle">
<button id="btn_getRandomArticle" class="button button-glow button-circle button-action button-caution"><i class="fa fa-random"></i></button>
<button class="button button-glow button-circle button-action button-primary"><i class="fa fa-star"></i></button>
<button id="btn_save"class="button button-glow button-circle button-primary"><i class="fa fa-floppy-o"></i></button>
<p id="text_saved"></p>
</div>
</div>
<div id="authorInfo" class="DailyArticle">
<div class="refresh">
<button id="btn_refresh" class="button button-raised button-action button-circle button-highlight"><i class="fa fa-refresh"></i></button>
</div>
<div class="authorName"></div>
<div class="authorAvatar"><img src="" class="authorAvatar-img"alt=""></div>
<div class="authorDes"></div>
</div>
</body>
<script>
// You can also require other files to run in this process
require('./renderer.js')
</script>
</html>
renderer.js
//module import
const ipc = require('electron').ipcRenderer;
var cheerio = require('cheerio'),
superagent = require('superagent'),
fs = require('fs'),
path = require('path')
;
var result_list=$("#DailyArticle"),
articleTitle=$(".articleTitle")[0],
articleContent=$('.articleContent')[0],
articleFooter=$('.articleFooter')[0],
authorAvatar=$('.authorAvatar')[0],
authorAvatarImg=$('.authorAvatar-img')[0],
authorName=$('.authorName')[0],
authorDes=$('.authorDes')[0]
;
//随机获取一篇文章
function getRandomArticle(){
superagent
.get('https://interface.meiriyiwen.com/article/random?dev=1')
.end(function (err, sres) {
if (err) throw err;
//获取文章的标题、内容、作者
let dailyArticle=eval("text="+sres.text);
console.log(dailyArticle);
articleTitle.innerHTML=dailyArticle.data.title;
articleContent.innerHTML=dailyArticle.data.content;
articleFooter.innerHTML=dailyArticle.data.author;
//将作者的名字传入百度百科API获取更多作者信息
let search_author=articleFooter.innerText;
//获取作者信息
//
getAuthorInfo(search_author);
});
}
//获取作者信息
function getAuthorInfo(search_author) {
superagent.get("http://baike.baidu.com/api/openapi/BaikeLemmaCardApi")
.query({
scope:103,
format:'json',
appid:379020,
bk_key:search_author,
// bk_key:'让·季奥诺', //test err: {}
bk_length:600
})
.end(function(err,authorres){
console.log(authorres);
console.log(authorres.text);
//若没有找到作者,返回错误信息
let errApiInfo={"errno":2}
if(authorres.text=="{}"){
authorName.innerText=search_author;
authorDes.innerText="未找到此作者相关信息";
return false;
}
else if (authorres.text=='{"errno":2}') {
authorName.innerText=search_author;
authorDes.innerText="未找到此作者相关信息";
return false;
}
else{
//将JSON字符串转为对象
var authorInfo=eval("text="+authorres.text);
// console.log(authorInfo);
//为图片框设置属性
$('.authorAvatar-img').attr({
src:authorInfo.image,
alt:authorInfo.title
});
//将作者相关信息填充到DOM中
authorName.innerText=authorInfo.title;
authorDes.innerText=authorInfo.abstract;
}
});
}
//页面加载时获取文章
getRandomArticle();
//按键监听
//
//按钮:更换文章
$('#btn_getRandomArticle').on('click',function(){
getRandomArticle()
//回到顶部
var speed=200;
$('body,html ').animate({scrollTop:0},speed);
return false;
});
//按钮:保存文章到 ../saveArticles/ 文件夹下
$('#btn_save').on("click",function(event){
upLevelPath=path.resolve(__dirname,"..")
saveArticlesPath=path.join(upLevelPath,"saveArticles/"+articleTitle.innerText+".txt");
fs.exists(saveArticlesPath,function(exists){
if(exists){
console.log("文件已存在");
$('#text_saved').text("文件已存在于:"+saveArticlesPath);
return false;
}else{
fs.writeFile(saveArticlesPath,articleContent.innerText+articleFooter.innerText,function(err){
if(!err)
console.log("保存成功");
$('#text_saved').text("文本保存于:"+saveArticlesPath);
}
)
}
}
);
console.log("save");
});
//长按进行文章另存为的操作-未完成
var timeout;
$('#btn_save').on("mousedown",function(){
timeout=setTimeout(function(){
ipc.send('save-dialog');
console.log("long click");
},1000);
});
$('#btn_save').on("mouseup",function(){
clearTimeout(timeout);
})
ipc.on('saved-fileDirectory', function (event, path) {
if (!path) path = '无路径';
$('#text_saved').innerHTML = `选择的路径: ${path}`
})
//刷新按钮:重新获取作者信息
$('#btn_refresh').on("click",function(){
getAuthorInfo(articleFooter.innerText);
});
在main.js里面添加上 "打开保存文件对话框的" 监听
//保存文章的监听
const ipc = require('electron').ipcMain
const dialog = require('electron').dialog
ipc.on('save-dialog', function (event) {
defaultPath_url=url.format({
pathname: path.join(__dirname, 'saveArticles/'),
protocol: 'file:',
slashes: true
})
const options = {
title: '保存文本到',
defaultPath:defaultPath_url,
filters:[
{name:'文本文件', extensions:['txt']}
]
}
网友评论